我可以在输入元素中制作我的标签(我的“消失的文本”):
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
颜色。我明白为什么会发生这种情况,但无法完全了解如何在输入字段中输入值时将值保持为黑色 #000
颜色。
在此先感谢您的帮助和教育!
最佳答案
HTML5
HTML5 为 <input>
带来了一个方便的属性标签名为 placeholder
这使得 native 支持此功能。
<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
指示何时淡化文本。
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()
.
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/