JS实现表单中点击小眼睛显示隐藏密码框中的密码

领导交个一个任务,要求在表单中点击小眼睛显示隐藏密码框中的密码!在一些网站中经常会用到这样的功能,今天小编就给大家分享我的实现思路及代码

准备:

1.两张png图片,一张睁眼,一张闭眼,可以到阿里巴巴矢量图库寻找(免费下载)

JS实现表单中点击小眼睛显示隐藏密码框中的密码
JS实现表单中点击小眼睛显示隐藏密码框中的密码

最终效果图

JS实现表单中点击小眼睛显示隐藏密码框中的密码
JS实现表单中点击小眼睛显示隐藏密码框中的密码

css样式部分,样式可根据自己喜好设置,没有过硬要求

<style>
    div:first-child {
      width: 300px;
      height: 50px;
      background-color: red;
      color: white;
      margin: 20px auto;
      text-align: center;
      line-height: 50px;
    }

    div:nth-child(2) {
      position: relative;
      width: 300px;
      height: 50px;
      margin: 100px auto;
    }
    input {
      width: 300px;
      height: 46px;
      border: 0px white;
      border-bottom: 1px solid black;
      outline: none;
    }
    #eyes {
      width: 18px;
      position: absolute;
      top: 27px;
      right: 2px;
    }
  </style>

 

主体部分

 <div>
    密码
  </div>
  <div>
    <input type="password">
    <!--默认闭眼图-->
    <label><img src="1.png" alt="" id="eyes"></label>
  </div>

 

js部分

<script>
      //获取元素(两种方式都可以)
    var input = document.querySelector('input')
    var imgs = document.getElementById('eyes');
    //下面是一个判断每次点击的效果
    var flag = 0;
    imgs.onclick = function () {
      if (flag == 0) {
        input.type = 'text';
        eyes.src = '2.png';//睁眼图
        flag = 1;
      } else {
        input.type = 'password';
        eyes.src = '1.png';//闭眼图
        flag = 0;
      }
    }
  </script>

总结