首页 > 解决方案 > 防止在密码字段中触发按键事件

问题描述

我正在编写一个脚本来捕获给定 HTML 页面中的所有按键。

现在我有一个基本的工作脚本

document.onkeypress = function(event){
    var evtobj=window.event? event : e;
    if (evtobj.altKey || evtobj.ctrlKey || evtobj.shiftKey)
        console.log("'Alt', 'Ctrl', or 'Shift' key pressed");
    console.log(String.fromCharCode(evtobj.keyCode));
}

现在,如果事件在密码字段上触发,我想阻止此函数触发。

即使事件触发了我应该如何继续识别element是一个input盒子并且typepassword

我猜应该使用event.target.

标签: javascriptkeypressevent-listener

解决方案


您也可以通过检查输入的类型来执行此操作,event.target.type这将返回输入的类型。

<input type="password">
document.onkeypress = function(event){
  if(event.target.type != 'password'){
    var evtobj=window.event? event : e;
    if (evtobj.altKey || evtobj.ctrlKey || evtobj.shiftKey)
        console.log("'Alt', 'Ctrl', or 'Shift' key pressed");
    console.log(String.fromCharCode(evtobj.keyCode));
  }
}

推荐阅读