Javascript 输入时的默认文本

Javascript 输入时的默认文本,javascript,html,textinput,Javascript,Html,Textinput,如何在输入字段上设置空白默认文本,并在元素处于活动状态时将其清除。在现代浏览器中,您可以在字段上设置占位符属性以设置其默认文本 <input type="text" placeholder="Type some text" id="myField" /> 演示:使用onFocus和onBlur事件可以实现这一点,即: onfocus="if(this.value=='EGTEXT')this.value=''" 及 完整示例如下所示: <input name="examp

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

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

<input type="text" placeholder="Type some text" id="myField" />

演示:

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

onfocus="if(this.value=='EGTEXT')this.value=''" 

完整示例如下所示:

<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'" />

声明非活动和活动状态的样式:

.active {
    color: black;
}

.inactive {
    color: #909090;
}
添加Javascript以处理状态的更改:

function toggleText(el)
{
    var v = el.value;

   //Remove text to allow editing
    if(v=="Default text") {
        el.value = "";
        el.className = "active";
    }
    else {
         //Remove whitespace
        if(v.indexOf(" ")!=-1) {
            split = v.split(" ").join("");
            v = split;
        }

          //Change to inactive state
        if(v=="") {
            el.value = "Default text";
            el.className = "inactive";
        }
    }
}
添加带有默认值集的输入框、
inactive
类集和指向
toggleText()
函数的Javascript处理程序(如果您愿意,可以使用它)


从可用性的角度来看,输入组件中的文本应仅为用户输入目的而保留。如果用户未触及输入中可能的默认值,则该值应有效

如果占位符文本是关于如何填充输入的提示,那么最好将其放在输入附近,在输入填充后也可以看到。此外,在文本组件内使用占位符文本可能会导致问题,例如盲文设备


如果使用占位符文本,不管可用性指南如何,都应该确保以不引人注目的方式使用占位符文本,以便在不使用javascript或关闭js的情况下使用用户代理。

我找到了jQuery插件()并使用它:)

或者干脆

<input name="example" type="text" id="example" value="Something" onfocus="value=''" />

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

您可以使用此插件(我是合著者)

它克隆一个输入字段并将其放在那里

它可以在IE、Firefox、Chrome甚至iPhone Safari上运行,而iPhone Safari存在着著名的焦点问题

这样,您就不必担心在提交之前清除输入字段


如果只想使用HTML5,只需在输入字段上使用属性“占位符”

就可以使用占位符属性。
np<代码>


检查我所做的是为现代浏览器添加占位符属性:

<input id='search' placeholder='Search' />

这对我很有用。

Duplicate:我找到了jQuery插件()并使用了它:)我知道这是个老问题,但我写了一个非常轻量级的插件,因为我不喜欢其他插件。您只需将其包括在内,将
占位符
作为类添加到输入中,然后将默认文本放入
标题
属性中。酷,这是HTML5的一部分,哇,我不知道。谢谢你的链接!
<input type="text" value="Default text" class="inactive" onFocus="toggleText(this);" onBlur="toggleText(this);">
<input name="example" type="text" id="example" value="Something" onfocus="value=''" />
<input id='search' placeholder='Search' />
var placeholder = $('search').attr('placeholder');
//Set the value
$('search').val(placeholder);

//On focus (when user clicks into the input)
$('search').focus(function() {
   if ($(this).val() == placeholder)
     $(this).val('');
});

//If they focus out of the box (tab or click out)
$('search').blur(function() {
   if ($(this).val() == '')
     $(this).val(placeholder);
});