纯 JS 设置文本框的默认提示

HTML5 中有个新特性叫 placeholder,一般用它来描述输入字段的预期值,适用于 text、search、password 等类型的 input 以及 textarea。示例如下:

<input type="text" placeholder="请输入文本"><br>
<input type="search" placeholder="请输入查询关键字"><br>
<input type="password" placeholder="请输入密码"><br>
<textarea placeholder="请输入描述"></textarea>

对用户来说,placeholder 就是文本框中的输入提示信息,往往是对预期值或预期格式的简短描述。该提示在用户输入之前显示在文本框中,在用户开始输入之后,该提示就会消失,此时文本框中显示的是用户输入的内容。而如果文本框被置空,则该提示会再次显示出来。

然而遗憾的是,早些年还有大量的 IE9 以及更低版本的 IE 用户,这些浏览器都不支持 placeholder 属性。所以那会儿做项目的时候,经常需要用 JS 来模拟 placeholder,以达到类似的效果。实现代码如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>纯 JS 设置文本框的默认值</title>
</head>
<body>
    <!-- 写法一,设置默认值为 111 -->
    <input type="text" value="111" onfocus="if(this.value == '111'){this.value = ''}"
        onblur="if(this.value == ''){this.value = '111'}" />
    <br />
    <!-- 写法二,设置默认值为 222,为了效果更逼真,将默认值设置为灰色 -->
    <input type="text" value="222" style="color: #cccccc"
        onfocus="if(this.value == '222'){this.value = ''; this.style.color = '#333333'}"
        onblur="if(this.value == ''){this.value = '222'; this.style.color = '#cccccc'}" />
    <br />
    <!-- 写法三,设置默认值为 333,其实上面写法中的 this 可以省略 -->
    <input type="text" value="333" style="color: #cccccc"
        onfocus="if(value == '333'){value = ''; style.color = '#333333'}"
        onblur="if(value == ''){value = '333'; style.color = '#cccccc'}" />
    <br />
    <!-- 写法四,设置默认值为 444,将 html 中的 js 代码提取出来 -->
    <input type="text" value="444" style="color: #cccccc" id="txt4" />
    <script>
        var txt4 = document.getElementById("txt4");
        txt4.onfocus = function () {
            if (this.value == '444') {
                this.value = '';
                this.style.color = '#333333';
            }
        }
        txt4.onblur = function () {
            if (this.value == '') {
                this.value = '444';
                this.style.color = '#cccccc';
            }
        }
    </script>
    <br />
    <!-- 写法五,设置默认值为 555,换一种绑定事件的方式 -->
    <input type="text" value="555" style="color: #cccccc" id="txt5" />
    <script>
        var txt5 = document.getElementById("txt5");
        txt5.addEventListener("focus", function (){
            if (this.value == '555') {
                this.value = '';
                this.style.color = '#333333';
            }
        });
        txt5.addEventListener("blur", function () {
            if (this.value == '') {
                this.value = '555';
                this.style.color = '#cccccc';
            }
        });
    </script>
</body>
</html>

本文链接http://www.cnblogs.com/hanzongze/p/js-self-placeholder.html
版权声明:本文为博客园博主 韩宗泽 原创,作者保留署名权!欢迎通过转载、演绎或其它传播方式来使用本文,但必须在明显位置给出作者署名和本文链接!个人博客,能力有限,若有不当之处,敬请批评指正,谢谢!

posted @ 2019-07-21 12:55  韩宗泽  阅读(3524)  评论(0编辑  收藏  举报
回到顶部