javascript - 在字段中显示 'ghosted' 示例文本,然后将其清除 onblur

标签 javascript jquery html forms field

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

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

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

非常感谢 Hive Mind!

最佳答案

<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 会使它变小,但我不使用它。

关于javascript - 在字段中显示 'ghosted' 示例文本,然后将其清除 onblur,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/285139/

相关文章:

javascript - 下拉 onchange 事件直到第二个实例才触发

html - 滚动条未完全显示 Div 中的值

javascript - 通过 AJAX 加载 Google Maps API,控制台错误

Javascript:将字符串转换为完整的月份到日期对象

javascript - css,如何根据表格中的事件行设置滚动位置

javascript - 如何在可扩展菜单中正确显示标题?

css - 如何在网页中使用多种 Google 字体?

javascript - Canvas :JavaScript 未捕获错误:INDEX_SIZE_ERR:DOM 异常 1

jquery - 网站站长工具中的文件夹出现 404 错误

javascript - 如何从 ul li 项目中获取文本?