1

我正在尝试复制 Firefox 搜索框中使用的效果,如果搜索字段没有焦点(用户没有在其中单击),它只会以灰色文本显示Google。然后,当用户在框中单击时,文本被删除,他们可以填写他们的搜索词。

我想用它来为 Web 表单提供示例字段数据。

JQuery 语法比纯 javascript 更可取,但纯 JS 也可以。

非常感谢蜂巢思维!

4

6 回答 6

6
<style type='text/css'>
      input #ghost { color: #CCC; }
      input #normal { color: #OOO; }
</style>

<script type='text/javascript'> 
    function addTextHint(elem, hintText)
    {       
        if (elem.value == '')   
        {       
            elem.value = hintText;
            elem.style.className = 'ghost';
        }

        elem.onfocus = function ()
        {           
            if (elem.value == hintText)         
            {
                elem.value = '';
                elem.className = 'normal';
            }
        }

        elem.onblur = function ()
        {
            if (elem.value == '')
            {
                elem.value = hintText;
                elem.className = 'ghost';
            }
        }           
    }

    addTextHint(document.getElementById('foobar'),'Google');
</script>

刚刚为你准备了这个。我敢肯定,jQuery 会使它变小,但我不使用它。

于 2008-11-12T20:09:03.040 回答
3

这种技术非常常用,现在 HTML 规范通过输入标记的占位符属性明确支持它:
HTML 占位符属性

大多数浏览器已经支持它,对于较旧的浏览器,有一个提供 shim 实现的 jquery 插件,可以在此处找到。

有关占位符文本的样式,请参阅此(包括实时示例):
HTML5 Placeholder Styling with CSS

于 2014-02-04T11:52:23.910 回答
2

另一种方法是使用一些 CSS,使用您想要的背景文本创建一个图像,并将其设置为文本框的背景图像,然后当文本框获得焦点时,您可以切换样式以删除该背景图像。

于 2008-11-12T20:15:03.403 回答
2

jQuery实现

<input type="text" id = "textField" value="Google" class="RegularText GhostText" />

<style>
.GhostText{color:#DDD}
.RegularText{color:#CCC}
</style>

<script type="text/javascript" language="javascript">
$("#textField").blur(function(e){
    if ($.trim(e.target.value) == "") {
        e.target.value = e.target.defaultValue;
        e.target.toggleClass("GhostText");
    }
});
$("#textField").focus(function(e){
    if ($.trim(e.target.value) == e.target.defaultValue) {
        e.target.value = "";
        e.target.toggleClass("GhostText");
    }
});
</script>
于 2012-10-18T17:38:07.797 回答
0

为什么要自己滚动?使用这个插件

于 2011-01-20T18:44:12.530 回答
-2
  $(选择器).text('谷歌');
  $(选择器).click(函数(){
    $(this).text('');
  });

可能有一种更优雅的方法可以做到这一点,但这假设您的框在页面加载时没有文本。如果是这样,您可以删除第一行。

我没有对此进行测试,但它应该可以工作。

于 2008-11-12T20:06:03.080 回答