问题描述
我想在html页面的给定textarea元素上模拟keydown事件。由于我使用的是chrome,因此我在变量上调用了 initKeyboardEvent
,并将我想要键入的keyCode传递给textarea。这是我试过的:
I want to simulate keydown events on a given textarea element in an html page. Since I am using chrome, I called initKeyboardEvent
on my variable and I passed the keyCode I want to type into the textarea. Here is what I tried:
var keyEvent = document.createEvent('KeyboardEvent');
keyEvent.initKeyboardEvent('keydown', true, false, null, 0, false, 0, false, 77, 0);
inputNode.dispatchEvent(keyEvent);
在此代码中,我输入字母 m
但是textarea只获取keyCode 13
,它是 Enter
键。所以,我尝试了一个我在网上看到的覆盖代码,它将值设置为keyCodeVal,但没有成功
In this code I'm typing the letter m
however the textarea is only getting the keyCode 13
which is the Enter
key. So, I tried an override code I saw online that sets the value to keyCodeVal, but with no success
var keyEvent = document.createEvent('KeyboardEvent');
Object.defineProperty(keyEvent, 'keyCode', {
get : function() {
return this.keyCodeVal;
}
});
keyEvent.initKeyboardEvent('keydown', true, false, null, 0, false, 0, false, 77, 0);
keyEvent.keyCodeVal = 77;
inputNode.dispatchEvent(keyEvent);
有没有人知道如何设置keyCode值?
Does anyone have an idea how to set the keyCode value?
推荐答案
非常非常接近...
您只需要重写'which'属性。以下是一些示例代码:
You just needed to override the 'which' property. Here's some sample code:
Podium = {};
Podium.keydown = function(k) {
var oEvent = document.createEvent('KeyboardEvent');
// Chromium Hack
Object.defineProperty(oEvent, 'keyCode', {
get : function() {
return this.keyCodeVal;
}
});
Object.defineProperty(oEvent, 'which', {
get : function() {
return this.keyCodeVal;
}
});
if (oEvent.initKeyboardEvent) {
oEvent.initKeyboardEvent("keydown", true, true, document.defaultView, false, false, false, false, k, k);
} else {
oEvent.initKeyEvent("keydown", true, true, document.defaultView, false, false, false, false, k, 0);
}
oEvent.keyCodeVal = k;
if (oEvent.keyCode !== k) {
alert("keyCode mismatch " + oEvent.keyCode + "(" + oEvent.which + ")");
}
document.dispatchEvent(oEvent);
}
示例用法:
Sample usage:
Podium.keydown(65);
注意:此代码不适用于IE,Safari或其他浏览器。那么,也许与Firefox。 YMMV。
Note: this code is not designed to work in IE, Safari, or other browsers. Well, maybe with Firefox. YMMV.
这篇关于Chrome中的Keydown Simulation通常会触发但不是正确的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!