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

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


当前回答

$('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">

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


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

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

你想要这样分配给onfocus:

if (this.value == this.defaultValue)
    this.value = ''
this.className = ''

这是onblur:

if (this.value == '')
    this.value = this.defaultValue
this.className = 'placeholder'

(如果你愿意,你可以使用一些更聪明的东西,比如框架函数,来进行类名切换。)

用一些CSS像这样:

input.placeholder{
    color: gray;
    font-style: italic;
}

我喜欢“知识奇库斯”的解决方案——简单明了。只需要在页面加载就绪时添加一个模糊调用,这将设置初始状态:

$('input[value="text"]').blur();