案例:密码输入框显示隐藏密码 原生JS书写
需求:点击按钮将密码框切换为文本框,并可以查看密码铭文
案例分析
- 核心思路:点击眼睛按钮,把密码框类型改为文本框就可以看见里面的密码
- 一个按钮两个状态,点击一次,切换为文本框,继续点击一次切换为密码框
- 算法:利用一个flag变量,来判断flag值,如果时 1 就切换为文本框, flag 设置为 0 ,如果是 0 就切换为密码框, flag 设置为 1
<!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: 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" id="pwd">
</div>
<script>
// 1. 获取元素
var eye = document.getElementById('eye');
var pwd = document.getElementById('pwd');
// 2. 注册事件,处理程序
var flag = 0;
eye.onclick = function() {
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>
标签:eye,输入框,pwd,文本框,JS,密码,flag,切换
From: https://www.cnblogs.com/zhuhukang/p/17110217.html