JS实现仿京东密码隐藏显示

25 阅读1分钟

前言

大家好,这次项目的需求需要用到隐藏和显示的图片,我是在iconfont-阿里巴巴矢量图标库中找到的, 下面是我实现原理的梳理。

html样式

<div class="box">
        <label for="">
            <img src="./图标库/眼睛_隐藏.png" alt="" id="eye">
        </label>
        <input type="password" name="" id="pwd">
    </div>

css样式

 .box {
            position: relative;
            width: 400px;
            border-bottom: 1px solid #ccc;
            margin: 100px auto;
        }
        .box input {
            width: 370px;
            height: 30px;
            border: 0;
            outline: none;
        }
        .box img {
            position: absolute;
            top: 1px;
            right: 1px;
            width: 24px;
        }

js样式

<script>
       //1.获取元素
       var eye = document.getElementById('eye');
       // var eye = document.getElementsByTagName('img');
       var pwd = document.getElementById('pwd');
       //2.注册事件 处理程序
       var asd = 0;
       eye.onclick = function() {
           if(asd == 0) {
               eye.src = "./图标库/眼睛_显示.png"
               pwd.type = 'text';
               asd = 1;
           } else {
               eye.src = "./图标库/眼睛_隐藏.png"
               pwd.type = 'password'
               asd = 0;
           }
           
       }
   </script>

汇总

全部代码如下 ```

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
    .box {
        position: relative;
        width: 400px;
        border-bottom: 1px solid #ccc;
        margin: 100px auto;
    }
    .box input {
        width: 370px;
        height: 30px;
        border: 0;
        outline: none;
    }
    .box img {
        position: absolute;
        top: 1px;
        right: 1px;
        width: 24px;
    }
</style>


<div class="box">
    <label for="">
        <img src="./图标库/眼睛_隐藏.png" alt="转存失败,建议直接上传图片文件" id="eye">
    </label>
    <input type="password" name="" id="pwd">
</div>
<script>
    //1.获取元素
    var eye = document.getElementById('eye');
    // var eye = document.getElementsByTagName('img');
    var pwd = document.getElementById('pwd');
    //2.注册事件 处理程序
    var asd = 0;
    eye.onclick = function() {
        if(asd == 0) {
            eye.src = "./图标库/眼睛_显示.png"
            pwd.type = 'text';
            asd = 1;
        } else {
            eye.src = "./图标库/眼睛_隐藏.png"
            pwd.type = 'password'
            asd = 0;
        }</script>

    }
</script>
```