我想在我的网页上的搜索框显示字“搜索”在灰色斜体。当框接收到焦点时,它看起来就像一个空文本框。如果其中已经有文本,则应该正常显示文本(黑色,非斜体)。这将帮助我避免混乱的标签。

顺便说一句,这是一个页面Ajax搜索,所以它没有按钮。


当前回答

你可以添加和删除一个特殊的CSS类,用JavaScript修改输入值onfocus/onblur:

<input type="text" class="hint" value="Search..."
    onfocus="if (this.className=='hint') { this.className = ''; this.value = ''; }"
    onblur="if (this.value == '') { this.className = 'hint'; this.value = 'Search...'; }">

然后在CSS中指定一个样式提示类,例如:

input.hint {
    color: grey;
}

其他回答

来自http://asp.net的AJAXToolkit用户


可以使用占位符=""属性 下面是一个演示:

<html>
<body>
// try this out!
<input placeholder="This is my placeholder"/>
</body>
</html>

你可以添加和删除一个特殊的CSS类,用JavaScript修改输入值onfocus/onblur:

<input type="text" class="hint" value="Search..."
    onfocus="if (this.className=='hint') { this.className = ''; this.value = ''; }"
    onblur="if (this.value == '') { this.className = 'hint'; this.value = 'Search...'; }">

然后在CSS中指定一个样式提示类,例如:

input.hint {
    color: grey;
}

我发现jQuery插件jQuery水印比上面的答案中列出的要好。为什么好吗?因为它支持密码输入字段。此外,设置水印(或其他属性)的颜色就像在CSS文件中创建.watermark引用一样简单。

我使用了一个简单的,一行javascript解决方案,它的工作很棒。这里有一个文本框和文本区域的例子:

    <textarea onfocus="if (this.value == 'Text') { this.value = ''; }" onblur="if (this.value == '') { this.value = 'Text'; }">Text</textarea>

    <input type="text" value="Text" onfocus="if (this.value == 'Text') { this.value = ''; }" onblur="if (this.value == '') { this.value = 'Text'; }">

唯一的“缺点”是在对字段值做任何事情之前在$_POST或Javascript验证中进行验证。意思是,检查字段的值是不是“Text”。