如何在HTML中实现输入正确密码后展示指定文本的功能
HTML密码验证展示内容实现方案
注意:本方案为纯前端实现,预设密码会明文存在页面源码中,仅可用于非敏感内容场景。若涉及高安全需求的内容,请搭配后端鉴权逻辑使用。
下面是可直接复制运行的完整代码:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>密码验证</title> <style> /* 隐藏的机密内容默认不显示 */ #secretContent { display: none; margin-top: 20px; padding: 15px; border: 1px solid #eee; border-radius: 4px; } .pwd-area { margin: 20px 0; } </style> </head> <body> <h3>请输入访问密码</h3> <div class="pwd-area"> <input type="password" id="pwdInput" placeholder="请输入密码"> <button id="submitBtn">提交</button> </div> <!-- 这里放你要展示的大段文本内容 --> <div id="secretContent"> 这里是你要展示的预先设置的大段文本内容,可以随便替换,支持HTML标签,比如<br> 换行、<strong>加粗</strong>、列表等等,所有HTML语法都生效。 </div> <script> // 在这里设置你的正确密码 const CORRECT_PASSWORD = 'test123' const pwdInput = document.getElementById('pwdInput') const submitBtn = document.getElementById('submitBtn') const secretContent = document.getElementById('secretContent') submitBtn.addEventListener('click', function() { const userInput = pwdInput.value.trim() if (userInput === CORRECT_PASSWORD) { // 密码正确,展示内容 secretContent.style.display = 'block' } else { // 密码错误,提示 alert('密码错误,请重试') pwdInput.value = '' pwdInput.focus() } }) // 支持按回车提交 pwdInput.addEventListener('keyup', function(e) { if(e.key === 'Enter') submitBtn.click() }) </script> </body> </html>
自定义修改方法
- 修改预设密码:替换
const CORRECT_PASSWORD = 'test123'里的test123为你想要设置的密码即可 - 修改展示内容:替换
id="secretContent"的div内部的内容为你需要展示的大段文本即可,支持所有HTML标签 - 运行方式:把上述代码复制到记事本,保存时后缀名改为
.html,双击文件即可在浏览器打开使用
内容的提问来源于stack exchange,提问作者user69420
相关产品推荐
相关产品推荐

