JS实现HTML5属性placeholder效果

南楼画角 提交于 2019-11-28 17:22:13

placeholder属于HTML5新增的一个属性,但是因为存在兼容问题,所以可以用JS来实现它的功能

思路:使用到两个事件:onfocus和onblur,当输入获得焦点时,判断输入的内容,使其为空。当输入框失去焦点时,判断输入框是否为空,如果为空的话,value值变回原来默认的值

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <style>
            input {
                    width: 200px;
                    height: 24px;
                    line-height: 24px;
                    border: 1px solid #999;
                    background: #FFF;
                    margin: 15px 0 0 100px;
                    padding: 4px;
                    color: #CCC;
            }
    </style>
</head>
<body>
       <input type="text" value="请输入姓名" id="txt1">
       <br>
       <input type="text" value="请输入电话" id="txt1">
       <br>
       <input type="text" value="请输入联系方式" id="txt1">
       <script>
           var aInp = document.getElementsByTagName("input")
           var str = [];
           for(var i=0;i<aInp.length;i++){
               aInp[i].index = i;
               console.log(i);
               str.push(aInp[i].value)
               console.log(str)
               aInp[i].onfocus = function(){
                   if(aInp[this.index].value == str[this.index]){
                       aInp[this.index].value = '';
                   }
               }
               aInp[i].onblur = function(){
                   if(aInp[this.index].value == ''){
                       aInp[this.index].value = str[this.index];
                   }
               }
           }
       </script>
</body>
</html>

效果如下:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!