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

时间:2018-01-25 12:04:27

标签: javascript html

我想建立一个密码提示屏幕,在输入正确的密码并按 Enter 后重定向您。但是,目前它只能通过点击"提交"按钮。我很感激有关如何调整此代码的任何帮助:

以下是我的代码现在的样子:



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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

您可以使用keyup事件来检测何时按下某个键,然后检查其代码是否为13,代码为 Enter 。如果是这样,您可以提交表单,或者在您的案例中致电checkPswd

<强>代码:

/* 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;
};