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]
我们可以通过使用document.getElementsByTagName() 来扩展上述解决方案以适用于所有input[type=text],循环它们并使用element.getAttribute() 检查type 属性。
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;
}
}