仿京东的密码显示与隐藏

点击眼睛按钮,把密码框类型改为文本框,看见密码
获取元素(按钮)
注册单击事件
使用一个全局变量flag,记录type的状态
根据flag的值,改变type和src

<body>
<style>
    .box{
     
        position: relative;
        width: 400px;
        border-bottom: 1px solid #cccccc;
        margin: 100px auto;
    }
    .box input{
     
        width: 370px;
        height: 30px;
        border: 0;
        outline: none;
    }
    .box img{
     
        position: absolute;
        top: 2px;
        right: 2px;
        width: 24px;
    }
</style>
<div class="box">
    <label for="">
        <img src="images/close.png" alt="" id="eye">
    </label>
    <input type="password" name="pwd" id="pwd">
</div>
<script>
    let flag = 0;
    let eye = document.getElementById('eye');
    let pwd = document.getElementById('pwd');
    eye.onclick = function () {
     
        if(flag==0){
     
            eye.src="images/open.png"
            flag=1;
            pwd.type = "txt";

        }
        else{
     
            flag = 0;
            eye.src="images/close.png"

            pwd.type = "password";
        }
    }
</script>

在这里插入图片描述

在这里插入图片描述

你可能感兴趣的:(web前端,js,javascript)