我想在html页面中的给定textarea元素上模拟keydown事件。由于我使用的是chrome,因此我调用initKeyboardEvent了变量,然后将要键入的keyCode传递到了textarea中。这是我尝试过的:
initKeyboardEvent
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,但没有成功
m
13
Enter
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值?
非常非常接近…
您只需要覆盖’which’属性。这是一些示例代码:
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); }
用法示例:
Podium.keydown(65);
注意:此代码不适用于IE,Safari或其他浏览器。好吧,也许使用Firefox。YMMV。