我可以在输入元素(我的“消失的文本”)中创建标签:
HTML格式
<input name="firstName" type="text" maxlength="40" value="Enter your first name"
onfocus="if(this.value==this.defaultValue)this.value=''"
onblur="if(this.value=='')this.value=this.defaultValue" />
然后调整它的样式,这样我消失的文本就会变淡(#333)。当我开始在字段中输入一个值时,文本是黑色的(#000)。
CSS
input[type=text] {
color: #333;
}
input[type=text]:focus {
color: #000;
}
在进入下一个输入字段之前,一切正常。然后,您刚刚输入的值变回
#333
颜色。我可以理解为什么会发生这种情况,但是如果输入字段中有一个值,我就不能很好地理解如何使值保持黑色。提前感谢您的帮助和教育!
最佳答案
HTML5
HTML5为名为<input>
的placeholder
标记带来了一个方便的属性,它支持此功能的本机支持。
jsFiddle
<input type="text" placeholder="Search..." />
支持
所有最新的浏览器都支持这个,IE9 and below don't however。
<label>
请注意,每个输入都应该具有placeholder attribute is not a replacemenr for the
<label>
tag,确保包含<input>
的标签,即使用户看不到它。<label for="search">Search</label>
<input id="search" placeholder="Search..." />
上面的
<label>
可以隐藏起来,因此它仍然可以用于辅助技术,例如:label[for=search] {
position:absolute;
left:-9999px;
top:-9999px;
}
跨浏览器解决方案
这是一个潜在的跨浏览器解决方案,我已经将代码从标记移到脚本标记,然后使用类
placeholder
指示何时淡入文本。jsFiddle
HTML格式
<input name="firstName" type="text" maxlength="40" value="Enter your first name"
class="placeholder" id="my-input" />
CSS
input[type=text].placeholder {
color: #999;
}
JS公司
<script type="text/javascript">
var input = document.getElementById('my-input');
input.onfocus = function () {
if (this.value == this.defaultValue && this.className == 'placeholder') {
this.value = '';
}
this.className = '';
};
input.onblur = function() {
if (this.value == '') {
this.className = 'placeholder';
this.value = this.defaultValue;
}
};
</script>
全部应用
input[type=text]
我们可以通过使用
input[type=text]
,遍历它们并使用document.getElementsByTagName()
检查type
属性,将上述解决方案扩展到所有element.getAttribute()
。jsFiddle
var input = document.getElementsByTagName('input');
for (var i = 0; i < input.length; i++) {
if (input[i].getAttribute('type') === 'text') {
input[i].onfocus = inputOnfocus;
input[i].onblur = inputOnblur;
}
}
function inputOnfocus () {
if (this.value == this.defaultValue && this.className == 'placeholder') {
this.value = '';
}
this.className = '';
}
function inputOnblur() {
if (this.value == '') {
this.className = 'placeholder';
this.value = this.defaultValue;
}
}
关于javascript - 如何在<input>元素内创建标签并设置其样式?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15672970/