JavaScript 显示和隐藏密码
本文将向您展示如何使用JavaScript隐藏/显示密码。在填写表单的过程中,有时我们会输入密码并想要查看我们已经输入了什么。为了查看密码,有一个复选框,点击它可以使字符可见。本文将使用JavaScript添加切换密码功能。
方法:
- 创建一个包含密码输入字段的HTML表单。
- 创建一个负责切换的复选框。
- 创建一个函数,响应用户点击复选框时的切换效果。
示例:
Password is geeksforgeeks.
So, on typing it will show like this *****************
And on clicking the checkbox it will show the characters: **geeksforgeeks**.
<!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>
Show and hide password using JavaScript
</title>
</head>
<body>
<strong>
<p>Click on the checkbox to show
or hide password:
</p>
</strong>
<strong>Password</strong>:
<input type="password" value="geeksforgeeks"
id="typepass">
<input type="checkbox" onclick="Toggle()">
<strong>Show Password</strong>
<script>
// Change the type of input to password or text
function Toggle() {
let temp = document.getElementById("typepass");
if (temp.type === "password") {
temp.type = "text";
}
else {
temp.type = "password";
}
}
</script>
</body>
</html>
输出:

极客教程