防止在密码字段中触发按键事件

时间:2019-01-23 06:08:04

标签: javascript keypress event-listener

我正在研究一个脚本,以捕获给定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));
}

现在,我要防止此事件在密码字段上触发的情况下触发。

即使事件触发了,我该如何继续识别elementinput框而typepassword

我猜应该使用event.target完成。

2 个答案:

答案 0 :(得分:2)

您还可以通过使用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));
  }
}

答案 1 :(得分:1)

<input type='password' name='password'/>

document.onkeypress = function(event){
    var containerName = event.target.name;
    if (containerName !== '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));
    }
 }

这应该可以解决您的问题