在字段中显示"幻影"示例文本,然后将其清除为onblur

1 html javascript forms jquery field

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

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

JQuery语法比普通的javascript更好,但是普通的JS也没关系.

非常感谢Hive Mind!

Fly*_*wat 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>
Run Code Online (Sandbox Code Playgroud)

刚刚为你鞭打了这个.jQuery会让它更小我确定,但我不使用它.