js中的input 显示与隐藏

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <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;
            outline: none;
            border: 0;
        }
        
        .box img {
     
     
            position: absolute;
            top: 2px;
            right: 2px;
            width: 24px;
        }
    </style>
</head>

<body>
    <div class="box">
        <label for="">
            <img src="images/close.png" alt="" id="eye">
        </label>
        <input type="password" name="" id="pwd">
    </div>
    <script>
        var eye = document.getElementById('eye');
        var pwd = document.getElementById('pwd');
        var flag = 0; //默认是0
        eye.onclick = function() {
     
      //点击事件  类型改为文本
            if (flag == 0) {
     
     
                pwd.type = 'text'; //类型改为文本框
                eye.src = 'images/open.png';
                flag = 1; // flag赋值为1 ,再次点击不会执行if语句 执行else语句
            } else {
     
     
                pwd.type = 'password';
                eye.src = 'images/close.png';
                flag = 0;
            }
        }
    </script>
</body>

</html>

猜你喜欢

转载自blog.csdn.net/llt299022/article/details/113725045