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

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


当前回答

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

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

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

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

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

其他回答

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

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

下面是一个带有谷歌Ajax库缓存和一些jQuery魔法的函数示例。

这将是CSS:

<style type="text/stylesheet" media="screen">
    .inputblank { color:gray; }  /* Class to use for blank input */
</style>

这将是JavaScript代码:

<script language="javascript"
        type="text/javascript"
        src="http://www.google.com/jsapi">
</script>
<script>
    // Load jQuery
    google.load("jquery", "1");

    google.setOnLoadCallback(function() {
        $("#search_form")
            .submit(function() {
                alert("Submitted. Value= " + $("input:first").val());
                return false;
        });

        $("#keywords")
            .focus(function() {
                if ($(this).val() == 'Search') {
                    $(this)
                    .removeClass('inputblank')
                    .val('');
                }
            })
            .blur(function() {
                if ($(this).val() == '') {
                    $(this)
                    .addClass('inputblank')
                    .val('Search');
                }
            });
    });
</script>

这就是HTML:

<form id="search_form">
    <fieldset>
        <legend>Search the site</legend>
            <label for="keywords">Keywords:</label>
        <input id="keywords" type="text" class="inputblank" value="Search"/>
    </fieldset>
</form>

我希望这足以使您对GAJAXLibs和jQuery产生兴趣。


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

<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" />

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

我使用了一个简单的,一行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”。