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

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


当前回答

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

其他回答

使用背景图像来渲染文本:

 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");
        }
    });
});

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

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

前段时间我在我的网站上发布了一个解决方案。要使用它,请导入一个.js文件:

<script type="text/javascript" src="/hint-textbox.js"></script>

然后用CSS类hintTextbox注释任何你想要有提示的输入:

<input type="text" name="email" value="enter email" class="hintTextbox" />

更多的信息和例子可以在这里找到。

你可以很容易地有一个框读“搜索”,然后当焦点改变到它有文本被删除。就像这样:

< 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用户:naspinski的jQuery链接似乎坏了,但试试这个: http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/

你会得到一个免费的jQuery插件教程作为奖励。:)