如何使用 JavaScript 切换密码可见性?
本文中,我们将把密码隐藏为 ****。可以通过使用按钮切换其可见性来显示密码。我们将创建 JavaScript 函数,以便在单击切换按钮时显示隐藏的密码。
方法
单击切换按钮后,将呈现 display password JavaScript 函数。
这将会更改应用于将显示密码的 HTML 输入标记上的 CSS 属性。
我们可以再次切换以再次隐藏密码。
示例
在以下示例中,我们使用 checkboxcheckbox 切换密码的可见性。单击 checkbox 按钮后将显示密码,否则将隐藏密码。
# index.html
<!DOCTYPE html>
<html>
<head>
<title>
Toggle Password Visibility
</title>
</head>
<body>
<h2 style="color:green">
Welcome To Tutorials Point
</h2>
<div class="container">
<h3 class="mt-5 mb-5 text-center">Toggle password visibility</h3>
<div class="form-group">
<label for="ipnPassword">Password</label>
<div class="input-group mb-3">
<input type="password" class="form-control" id="ipnPassword"/>
<div class="input-group-append">
<input type="checkbox" class="btn btn-outline-secondary" type="button" id="btnPassword">Show Password
</button>
</div>
</div>
</div>
</div>
</body>
<script>
// step 1
const ipnElement = document.querySelector('#ipnPassword')
const btnElement = document.querySelector('#btnPassword')
// step 2
btnElement.addEventListener('click', function() {
// step 3
const currentType = ipnElement.getAttribute('type')
// step 4
ipnElement.setAttribute('type',currentType === 'password' ? 'text' : 'password')
})
</script>
</html>输出


广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP