简体   繁体   English

如何在Enter按下时触发HTML密码输入

[英]How to trigger HTML password input on enter press

I'd like to build a password prompt screen that redirects you somewhere after entering the correct password and pressing Enter . 我想建立一个密码提示屏幕,在输入正确的密码并按Enter后将您重定向到某个地方。 However, currently it only works by clicking the "Submit" button. 但是,当前只能通过单击“提交”按钮来工作。 I'd appreciate any help on how to adapt this code: 感谢您对如何修改此代码的任何帮助:

Here's what my code looks like for now: 这是我的代码现在的样子:

 function checkPswd() { var confirmPassword = "asdf"; var password = document.getElementById("pswd").value; if (password == confirmPassword) { window.location.replace('http://www.google.com'); } } 
 @import url('https://fonts.googleapis.com/css?family=VT323'); body { background-color: #ffffff; display: table; } .div1 { height: 100%; width: 100%; display: table; position: absolute; top: 0; left: 0; } .div2 { text-align: center; display: table-cell; vertical-align: middle; font-family: VT323; font-size: 25px; color: #656262; } .box { text-align: center; font-size: 20px; font-family: VT323; outline: none; width: 250px; height: 35px; border: none; border-bottom: 2px solid #656262; } .confirm { border: none; font-size: 20px; font-family: VT323; margin-top: 10px; color: #656262; background-color: rgba(0, 0, 0, 0); cursor: pointer; } 
 <div class="div1"> <div class="div2"> <form> <input class="box" type="password" placeholder="123" id="pswd"> <br> <input class="confirm" type="button" value="SUBMIT" onclick="checkPswd();" /> </form> </div> </div> 

You can use the keyup event to detect when a key is pressed and then check if its code is 13 , the code of Enter . 您可以使用keyup事件来检测何时按下某个键,然后检查其代码是否为13 (即Enter的代码)。 If so, you can submit your form, or in your case call checkPswd . 如果是这样,您可以提交表格,或者致电checkPswd

Code: 码:

/* Cache the password input. */
var pswd = document.getElementById("pswd");

/* Call 'checkPswd' when the 'Enter' key is released. */
pswd.onkeyup = function (e) {
   if (e.which == 13) checkPswd();
};

/* Prevent the form from submitting. */
pswd.parentElement.onsubmit = function () {
   return false;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM