输入时的默认文本

Jar*_*aro 29 html javascript textinput

如何在输入字段上设置空白默认文本,并在元素处于活动状态时清除它.

mof*_*off 69

在现代浏览器中,您可以placeholder在字段上设置属性以设置其默认文本.

<input type="text" placeholder="Type some text" id="myField" />
Run Code Online (Sandbox Code Playgroud)

但是,在旧版浏览器中,您可以使用JavaScript捕获焦点并模糊事件:

var addEvent = function(elem, type, fn) { // Simple utility for cross-browser event handling
    if (elem.addEventListener) elem.addEventListener(type, fn, false);
    else if (elem.attachEvent) elem.attachEvent('on' + type, fn);
},
textField = document.getElementById('myField'),
placeholder = 'Type some text'; // The placeholder text

addEvent(textField, 'focus', function() {
    if (this.value === placeholder) this.value = '';
});
addEvent(textField, 'blur', function() {
    if (this.value === '') this.value = placeholder;
});
Run Code Online (Sandbox Code Playgroud)

演示:http://jsbin.com/utecu

  • 很酷,它是HTML 5的一部分,http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#attr-input-placeholder (3认同)

Kyl*_*ndo 14

使用onFocusonBlur事件可以实现这一点,即:

onfocus="if(this.value=='EGTEXT')this.value=''" 
Run Code Online (Sandbox Code Playgroud)

onblur="if(this.value=='')this.value='EGTEXT'"
Run Code Online (Sandbox Code Playgroud)

完整的例子如下:

<input name="example" type="text" id="example" size="50" value="EGTEXT" onfocus="if(this.value=='EGTEXT')this.value=''" onblur="if(this.value=='')this.value='EGTEXT'" />
Run Code Online (Sandbox Code Playgroud)


mon*_*ike 5

或者简单地

<input name="example" type="text" id="example" value="Something" onfocus="value=''" />
Run Code Online (Sandbox Code Playgroud)

一旦清除该框,这将不会回发默认文本,但也将允许用户清除该框并在自动完成脚本的情况下查看所有结果。