案例分析`
登录注册页面中,当我们输入密码时,密码显示的是不可见的,是属于密码框类型,点击小眼睛之后显示密码。
**核心思路:**1.点击眼睛按钮,把不可见的密码框类型改成可见的文本框就可看见里面的密码。
2.一个按钮分两个状态,点击一次,切换为可见的文本框,继续点击一次切换为密码框不可见
算法:
利用一个flag变量,来判断flag的值,如果是1就切换为文本框,flag设置为0;如果是0就切换为密码框,flag设置为1
css部分
<style>
.box {
position: relative;
width: 400px;
border-bottom: 1px solid #ccc;
margin: 100px auto;
}
.box input {
width: 370px;
height: 40px;
border: 0;
/* 取消蓝色边框 */
outline: none;
}
.box img {
position: absolute;
top: 12px;
right: 2px;
width: 24px;
}
</style>
javascript部分
<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>
总代码
<!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: 40px;
border: 0;
/* 取消蓝色边框 */
outline: none;
}
.box img {
position: absolute;
top: 12px;
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>
</html>