我想在我的网页上的搜索框显示字“搜索”在灰色斜体。当框接收到焦点时,它看起来就像一个空文本框。如果其中已经有文本,则应该正常显示文本(黑色,非斜体)。这将帮助我避免混乱的标签。
顺便说一句,这是一个页面Ajax搜索,所以它没有按钮。
我想在我的网页上的搜索框显示字“搜索”在灰色斜体。当框接收到焦点时,它看起来就像一个空文本框。如果其中已经有文本,则应该正常显示文本(黑色,非斜体)。这将帮助我避免混乱的标签。
顺便说一句,这是一个页面Ajax搜索,所以它没有按钮。
当前回答
我使用了一个简单的,一行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”。
其他回答
$('input[value="text"]').focus(function(){
if ($(this).attr('class')=='hint')
{
$(this).removeClass('hint');
$(this).val('');
}
});
$('input[value="text"]').blur(function(){
if($(this).val() == '')
{
$(this).addClass('hint');
$(this).val($(this).attr('title'));
}
});
<input type="text" value="" title="Default Watermark Text">
你可以很容易地有一个框读“搜索”,然后当焦点改变到它有文本被删除。就像这样:
< onfocus =“这个输入。价值=“类型”=“文本”=“搜索”/>
当然,如果你这样做,用户自己的文本将消失时,他们点击。所以你可能想要使用更健壮的东西:
<input name="keyword_" type="text" size="25" style="color:#999;" maxlength="128" id="keyword_"
onblur="this.value = this.value || this.defaultValue; this.style.color = '#999';"
onfocus="this.value=''; this.style.color = '#000';"
value="Search Term">
这叫做“水印”。
我找到了jQuery插件jQuery水印,不像第一个答案,它不需要额外的设置(原始答案也需要在表单提交之前进行特殊调用)。
您可以使用HTML中的placeholder属性设置占位符(浏览器支持)。可以使用CSS更改字体样式和颜色(尽管浏览器支持有限)。
input[type=search]:::-webkit-input-placeholder {/* Safari, Chrome(, Opera?) */ 颜色:灰色; 字体样式:斜体; } input[type=search]:-moz-placeholder {/* Firefox 18- */ . txt 颜色:灰色; 字体样式:斜体; } input[type=search]::-moz-占位符{/* Firefox 19+ */ 颜色:灰色; 字体样式:斜体; } input[type=search]:-ms-input-placeholder {/* IE (10+? 颜色:灰色; 字体样式:斜体; } <input placeholder="Search" type=" Search" name="q">
使用jQuery Form Notifier -它是最流行的jQuery插件之一,并且不会遭受其他jQuery建议的错误(例如,你可以自由地设置水印样式,而不用担心它会被保存到数据库中)。
jQuery水印直接在表单元素上使用单一的CSS样式(我注意到应用于水印的CSS字体大小属性也会影响文本框——这不是我想要的)。加上jQuery水印是你可以拖拽文本到字段(jQuery表单通知不允许这一点)。
另一个由其他人建议(在digitalbrush.com),会意外地提交水印值到您的表单,所以我强烈建议反对它。