目标:
点击小眼睛后,
1、密码框变成文本框;
2、小眼睛图片由闭眼变成睁眼;
3、再次点击后,又变成闭眼+密码框
要想实现3,方法1:
则需要一个变量,来辅助判断当前input的属性,如果flag为0,则在点击后,将input的type属性改为text框,同时,再将flag值重新赋为1.此时,再次点击,又会进行判断,而这次的flag=1,所以,就直接将input的type属性改为了password
要想实现3,方法2:
直接对input的type属性进行判断,若为text,则改为password,若为password,则改为text。
代码如下:
<!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>
/*设置父盒子的样式*/
div {
position: relative;
width: 400px;
border-bottom: 2px solid #ccc;
margin: 100px auto;
}
/*设置密码框的样式*/
input {
width: 370px;
height: 30px;
border: none;
outline: none;
}
/*利用定位,设置小眼睛图片样式*/
img {
position: absolute;
top: 5px;
right: 1px;
width: 24px;
}
</style>
</head>
<body>
<!-- 结构:一个父盒子中有一个input表单,和一个图片 -->
<div>
<input type="password">
<i>
<img src="./images/close.png" alt="">
</i>
</div>
<script>
//步骤:
//1、获取元素
var ipt = document.querySelector('input');
var img = document.querySelector('img');
//2、注册事件
//方法1:
// var flag = 0;
// img.onclick = function() {
// if (flag == 0) {
// ipt.type = 'text';
// img.src = './images/open.png';
// flag = 1;
// } else {
// ipt.type = 'password';
// img.src = './images/close.png';
// flag = 0;
// }
// }
//方法2:
img.onclick = function() {
if (ipt.type === 'password') {
ipt.type = 'text';
img.src = './images/open.png';
} else {
ipt.type = 'password';
img.src = './images/close.png';
}
}
</script>
</body>
</html>
图片是找的京东上的眼睛睁闭图,如果想要测试,可以不用img图片,给 i 标签设置宽高并定位,给一个背景色,写JS时,可以将 i 标签设置成事件源,通过点击 i 标签的范围,来切换input的type属性。