源代码为:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<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: 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 = 'password';
eye.src = 'images/open.png';
flag = 1; // 赋值操作
} else {
pwd.type = 'text';
eye.src = 'images/close.png';
flag = 0;
}
}
</script>
</body>
</html>
由于自己更习惯用类选择器,所以想,为什么不能改用类选择器呢?遂做了以下修改:
<div class="box">
<label for="">
<img src="images/close.png" alt="" class="eye">
</label>
<input type="password" name="" class="pwd">
</div>
<script>
// 1. 获取元素
var eye = document.querySelector('.eye');
var pwd = document.querySelector('.pwd');
但是进入浏览器预览后,发现一个非常奇怪的现象:隐藏按钮要多点一次输入的文本才会变化,结果导致隐藏和显示的功能反过来了。
这到底是怎么回事?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
你默认是password,type=0
判断还是type为0input类型编password,写反了
改一下试一下
if (flag == 0) {
pwd.type = 'text';
eye.src = 'images/open.png';
flag = 1; // 赋值操作
} else {
pwd.type = 'password';
eye.src = 'images/close.png';
flag = 0;
}