在使用网上银行或者其他涉及到账户密码的场合中,为了保护账户安全,一般输入密码时都会显示为黑点或星号,但是有时候用户需要确认自己输入的密码是否正确,在这种情况下,就需要一个点击显示或隐藏密码的功能了。那...
在使用网上银行或者其他涉及到账户密码的场合中,为了保护账户安全,一般输入密码时都会显示为黑点或星号,但是有时候用户需要确认自己输入的密码是否正确,在这种情况下,就需要一个点击显示或隐藏密码的功能了。那么,怎么实现点击显示隐藏密码呢?
首先,在HTML中,我们需要用一个input标签来输入密码,同时需要加上type="password"属性,这样输入时才会显示为黑点或星号。下面是示例代码:
<input type="password" id="passwordInput"></input> label[for="passwordInput"] {
padding-left: 5px;
cursor: pointer;
}
label[for="passwordInput"]:before {
content: "显示密码";
padding-left: 10px;
}
label[for="passwordInput"]:after {
content: "隐藏密码";
margin-left: 5px;
}
label[for="passwordInput"]:hover:before,
label[for="passwordInput"]:hover:after {
color: #06c;
}
#passwordInput[type="password"] {
font-family: monospace;
}
#passwordInput[type="text"] {
font-weight: bold;
}
#passwordInput[type="password"] + label[for="passwordInput"]:before {
display: block;
}
#passwordInput[type="text"] + label[for="passwordInput"]:after {
display: block;
}
#passwordInput[type="password"] + label[for="passwordInput"]:after {
display: none;
}
#passwordInput[type="text"] + label[for="passwordInput"]:before {
display: none;
}
#passwordInput:checked {
/* 显示密码 */
-webkit-text-security: none;
text-security: none;
} var input = document.getElementById('passwordInput');
var label = document.querySelector('label[for="passwordInput"]');
label.addEventListener('click', function() {
input.type = (input.type === 'password') ? 'text' : 'password';
});