我想在我的网页上的搜索框显示字“搜索”在灰色斜体。当框接收到焦点时,它看起来就像一个空文本框。如果其中已经有文本,则应该正常显示文本(黑色,非斜体)。这将帮助我避免混乱的标签。
顺便说一句,这是一个页面Ajax搜索,所以它没有按钮。
我想在我的网页上的搜索框显示字“搜索”在灰色斜体。当框接收到焦点时,它看起来就像一个空文本框。如果其中已经有文本,则应该正常显示文本(黑色,非斜体)。这将帮助我避免混乱的标签。
顺便说一句,这是一个页面Ajax搜索,所以它没有按钮。
当前回答
最好的方法是使用某种JavaScript库(如jQuery或YUI)将JavaScript事件连接起来,并将代码放在外部的.js文件中。
但如果你想要一个快速的解决方案,这是你的内联html解决方案:
<input type="text" id="textbox" value="Search"
onclick="if(this.value=='Search'){this.value=''; this.style.color='#000'}"
onblur="if(this.value==''){this.value='Search'; this.style.color='#555'}" />
更新:增加了要求的着色材料。
其他回答
我使用了一个简单的,一行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”。
你可以添加和删除一个特殊的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;
}
最好的方法是使用某种JavaScript库(如jQuery或YUI)将JavaScript事件连接起来,并将代码放在外部的.js文件中。
但如果你想要一个快速的解决方案,这是你的内联html解决方案:
<input type="text" id="textbox" value="Search"
onclick="if(this.value=='Search'){this.value=''; this.style.color='#000'}"
onblur="if(this.value==''){this.value='Search'; this.style.color='#555'}" />
更新:增加了要求的着色材料。
另一种选择,如果你想让这个特性只适用于较新的浏览器,可以使用HTML 5的占位符属性提供的支持:
<input name="email" placeholder="Email Address">
在没有任何样式的情况下,在Chrome中看起来是这样的:
你可以在这里和HTML5的CSS占位符样式中尝试演示。
一定要检查该特性的浏览器兼容性。Firefox的支持是在3.7中添加的。Chrome浏览器没问题。Internet Explorer只在10中添加了支持。如果你的目标浏览器不支持输入占位符,你可以使用jQuery插件jQuery HTML5占位符,然后添加以下JavaScript代码来启用它。
$('input[placeholder], textarea[placeholder]').placeholder();
使用背景图像来渲染文本:
input.foo { }
input.fooempty { background-image: url("blah.png"); }
然后你所要做的就是检测value == 0并应用正确的类:
<input class="foo fooempty" value="" type="text" name="bar" />
jQuery JavaScript代码如下所示:
jQuery(function($)
{
var target = $("input.foo");
target.bind("change", function()
{
if( target.val().length > 1 )
{
target.addClass("fooempty");
}
else
{
target.removeClass("fooempty");
}
});
});