使用`which`属性以编程方式触发keydown事件

时间:2017-12-18 17:45:55

标签: javascript google-chrome javascript-events keydown onkeydown

如何以编程方式触发将which属性设置为所需值的Chrome上的keydown事件?

尝试

new KeyboardEvent('keydown', {
    'which':65,
    'charCode':65,
    'keyCode':65,
    'key':"a",
    'code':"KeyA",
});

但是当在输入的onKeyDown处理程序中接收该属性时,该事件的which,charCode and keyCode等于0key已正确设置为a

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

在Chrome中,这些事件属性的默认值为0且不可写(由于它们已被弃用)。您必须删除本机属性,然后重新创建它们:



var ke = new KeyboardEvent('keydown', {
    'key':"a",
    'code':"KeyA",
});

// Delete native event read-only properties with default values of 0
delete ke.keyCode;
delete ke.charCode;
delete ke.which;

// Create new custom properties that are read/write:
Object.defineProperty(ke, "keyCode", {"value" : 65});
Object.defineProperty(ke, "charCode", {"value" : 65});
Object.defineProperty(ke, "which", {"value" : 65});

var el = document.getElementById("key");

el.addEventListener("keydown", function(evt){
  console.log(evt.key, evt.code, evt.keyCode, evt.charCode, evt.which);
});

el.dispatchEvent(ke);

<input type="text" id="key">
&#13;
&#13;
&#13;