<style>
.box {
width: 400px;
margin: 50px auto;
position: relative;
}
#eye {
width: 24px;
position: absolute;
top: -2px;
right: 2px;
}
#pwd {
width: 400px;
outline: none;
border: none;
border-bottom: 1px solid #ccc;
}
</style>
<body>
<div class="box">
<label for="">
<img src="close.png" alt="" id="eye">
</label>
<input type="password" name="" id="pwd">
</div>
</body>
<script>
var eye = document.querySelector('#eye');
var pwd = document.querySelector('#pwd');
var flag = 0;
eye.onclick = function() {
if (flag == 0) {
eye.src = 'open.png';
pwd.type = 'text';
flag = 1;
} else {
eye.src = 'close.png';
pwd.type = 'password';
flag = 0;
}
}
</script>
<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: 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>
// 1. 获取元素
var eye = document.getElementById('eye');
var pwd = document.getElementById('pwd');
// 2. 注册事件 处理程序
var flag = 0;
eye.onclick = function() {
// 点击一次之后, flag 一定要变化
if (flag == 0) {
pwd.type = 'text';
eye.src = 'images/open.png';
flag = 1; // 赋值操作
} else {
pwd.type = 'password';
eye.src = 'images/close.png';
flag = 0;
}
}
</script>
</body>