在不需要后端支持的场景下,我们可以通过HTML搭建密码输入界面,结合JavaScript实现多密码验证逻辑,让同一个网页支持多个不同的合法密码访问。

实现基础密码输入页面
首先我们需要搭建一个简单的密码输入界面,包含输入框、提交按钮和提示区域,核心结构如下:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>多密码保护页面</title>
<style>
.container {
width: 300px;
margin: 100px auto;
text-align: center;
}
input {
width: 200px;
height: 30px;
margin: 10px 0;
padding: 0 10px;
}
button {
width: 220px;
height: 35px;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.tip {
color: red;
margin-top: 10px;
height: 20px;
}
</style>
</head>
<body>
<div class="container" id="loginBox">
<h3>请输入访问密码</h3>
<input type="password" id="passwordInput" placeholder="请输入密码">
<button onclick="checkPassword()">确认</button>
<div class="tip" id="tipText"></div>
</div>
<div class="container" id="contentBox" style="display: none;">
<h3>欢迎访问受保护内容</h3>
<p>这里是只有输入正确密码才能看到的内容</p>
</div>
</body>
</html>
多密码存储与校验逻辑
接下来我们需要定义合法的密码列表,然后编写校验函数,判断用户输入的密码是否在合法列表中。我们可以把合法密码存储在一个数组里,校验时遍历数组匹配即可:
// 定义多个合法密码,可根据需求增减
const validPasswords = ['pass123', 'test456', 'admin789'];
function checkPassword() {
// 获取输入框的值
const inputPwd = document.getElementById('passwordInput').value;
const tipElement = document.getElementById('tipText');
const loginBox = document.getElementById('loginBox');
const contentBox = document.getElementById('contentBox');
// 判断输入密码是否为空
if (!inputPwd) {
tipElement.textContent = '请输入密码';
return;
}
// 遍历合法密码数组,判断是否存在匹配项
let isMatch = false;
for (let i = 0; i < validPasswords.length; i++) {
if (inputPwd === validPasswords[i]) {
isMatch = true;
break;
}
}
// 根据匹配结果执行对应操作
if (isMatch) {
// 密码正确,隐藏登录框,显示内容区
loginBox.style.display = 'none';
contentBox.style.display = 'block';
} else {
tipElement.textContent = '密码错误,请重新输入';
// 清空输入框
document.getElementById('passwordInput').value = '';
}
}
优化校验体验
我们可以给密码输入框添加回车触发校验的功能,提升用户使用体验,添加如下JavaScript代码即可:
// 监听输入框的回车事件
document.getElementById('passwordInput').addEventListener('keydown', function(event) {
if (event.key === 'Enter') {
checkPassword();
}
});
注意事项
- 这种纯前端的密码保护方案安全性很低,密码会直接暴露在HTML和JS代码中,任何人查看页面源码都能获取所有合法密码,仅适合用于非敏感的内部测试、私人简单页面等场景。
- 如果需要更高的安全性,建议搭配后端验证,密码不要存储在前端代码中,而是通过后端接口校验。
- 合法密码数组如果需要动态修改,纯前端方案无法实现持久化,每次页面刷新都会恢复初始设置,有动态修改需求也需要后端支持。
HTMLJavaScript密码验证多密码设置前端安全修改时间:2026-07-12 15:45:25