实现原理:通过js的DOM操作更改表单元素的type属性(text/password)来控制表单输入框的文本是否可见。
//css部分
#d {
position: relative;
width: 200px;
height: 30px;
margin: 100px auto;
border-bottom: 1px solid #ccc;
}
#eyes {
position: absolute;
right: 2px;
top: 2px;
width: 20px;
height: 20px;
background-color: pink;
}
#d input {
display: inline-block;
text-indent: 5px;
outline: none;
}
//HTML部分
<div id="d">
<input type="password" name="" id="">
<div id="eyes"></div>
</div>
//JavaScript部分
var eye = document.getElementById('eyes');
var inp = document.querySelector('input');
eye.onclick = function() {
// if (inp.type == 'password') {
// inp.type = 'text';
// } else {
// inp.type = 'password';
// }
//两种写法
inp.type = inp.type == 'password' ? 'text' : 'password';
}
效果:点击粉色按钮切换输入框是否可见