前端显示隐藏密码案例


<!DOCTYPE html>
<html lang="en">

<head>
    <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 {
            border: 0;
            width: 350px;
            height: 30px;
            outline: none;
        }
        
        .box img {
            position: absolute;
            top: 2px;
            right: 2px;
            width: 24px;
        }
    </style>
</head>

<body>
    <div class="box">
        <label for=""></label>
        <img src="images/close.png" alt="" id='eye'>
        <input type="password" id='pwd'>

    </div>
    <script>
        // 核心思路:点击眼睛,把密码框类型改为文本框就可以看见里面的密码
        // 一个按钮两个状态,点击一次切换文本框,继续点击一次切换为密码框
        // 算法:利用一个flag变量。来判断flag的值,如果是1就切换为文本框,flag设置为0;如果是0;就切换为密码框,flag设置为1;
        var eye = document.getElementById('eye');
        var pwd = document.getElementById('pwd');
        var flag = 0;
        eye.onclick = function() {
            if (flag == 0) {
                eye.src = 'images/open.png';
                pwd.type = 'text';
                flag = 1;
            } else {
                eye.src = 'images/close.png';
                pwd.type = 'password';
                flag = 0;
            }

        }
    </script>
</body>

</html>

猜你喜欢

转载自blog.csdn.net/weixin_46002223/article/details/108180600