如何以编程方式触发将which
属性设置为所需值的Chrome上的keydown事件?
尝试
new KeyboardEvent('keydown', {
'which':65,
'charCode':65,
'keyCode':65,
'key':"a",
'code':"KeyA",
});
但是当在输入的onKeyDown
处理程序中接收该属性时,该事件的which,charCode and keyCode
等于0
。 key
已正确设置为a
。
感谢您的帮助
答案 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;