如何在无输入框的图片页面监听键盘输入"password"并跳转页面?
实现无输入框页面的键盘密码跳转功能
核心思路是监听全局键盘事件,记录用户输入的字符序列,当序列匹配预设密码时触发页面跳转。以下是具体实现代码:
完整代码示例
<!DOCTYPE html> <html> <head> <title>图片展示页</title> <style> body { margin: 0; overflow: hidden; } img { width: 100vw; height: 100vh; object-fit: cover; } </style> </head> <body> <!-- 替换为你的图片地址 --> <img src="your-image-path.jpg" alt="页面展示图"> <script> // 自定义配置 const targetPassword = 'password'; const redirectPageUrl = '/login.html'; // 替换为目标跳转页面 // 存储用户输入的字符序列 let userInput = []; // 监听全局键盘按下事件 document.addEventListener('keydown', function(e) { // 将按键转为小写,消除大小写差异 const pressedKey = e.key.toLowerCase(); // 添加当前按键到序列 userInput.push(pressedKey); // 仅保留和密码长度一致的末尾字符,避免序列过长 if (userInput.length > targetPassword.length) { userInput = userInput.slice(-targetPassword.length); } // 检查序列是否匹配密码 if (userInput.join('') === targetPassword) { // 跳转至目标页面 window.location.href = redirectPageUrl; // 重置输入序列,防止重复触发 userInput = []; } }); </script> </body> </html>
关键细节说明
- 事件监听:使用
document的keydown事件,确保能捕获页面任意位置的键盘输入。 - 大小写兼容:将按键转为小写,用户无论输入大写还是小写字母都能匹配密码。
- 序列管理:限制输入序列长度为密码长度,避免无效字符干扰,比如用户输入多余前缀时仍能正确匹配。
- 跳转后重置:匹配成功后重置输入序列,防止用户后续按键再次触发跳转。
内容的提问来源于stack exchange,提问作者Yubin Oh
相关产品推荐
相关产品推荐

