是否可以在JavaScript中以编程方式模拟按键事件?


当前回答

如果你可以使用jQuery 1.3.1:

函数simulateKeyPress(字符){ jQuery.event.trigger ({ 类型:键盘按键, 其中:character.charCodeAt (0) }); } $(函数(){ 美元(的身体).keypress(函数(e) { 警报(e.which); }); simulateKeyPress(“e”); }); < script src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/1.3.1/jquery.min.js " > > < /脚本

其他回答

让它工作的关键部分是认识到charCode, keyCode和这些都是不推荐的方法。因此,如果处理按键事件的代码使用这三个中的任何一个,那么它将收到一个伪答案(例如,默认值为0)。

只要使用非弃用的方法(如key)访问按键事件,就应该没问题。

为了完成,我添加了触发事件的基本Javascript代码:

const rightArrowKey = 39 const event = new KeyboardEvent('keydown',{'key':rightArrowKey}) document.dispatchEvent(事件)

我想模拟按Tab键……扩展Trevor的回答,我们可以看到像“tab”这样的特殊键确实会被按下,但我们看不到按“tab”会产生的实际结果……

尝试与调度这些事件的'activeElement'以及全局文档对象都-代码添加下面;

代码片段如下:

var element = document.getElementById("firstInput"); document.addEventListener("keydown", function(event) { console.log('we got key:', event.key, ' keyCode:', event.keyCode, ' charCode:', event.charCode); /* enter is pressed */ if (event.keyCode == 13) { console.log('enter pressed:', event); theKey = 'Tab'; attributes = { bubbles: true, key: theKey, keyCode: 9, charCode: 0, }; setTimeout(function() { /* event.keyCode = 13; event.target.value += 'b'; */ var e = new window.KeyboardEvent('focus', attributes); document.activeElement.dispatchEvent(e); e = new window.KeyboardEvent('keydown', attributes); document.activeElement.dispatchEvent(e); e = new window.KeyboardEvent('beforeinput', attributes); document.activeElement.dispatchEvent(e); e = new window.KeyboardEvent('keypress', attributes); document.activeElement.dispatchEvent(e); e = new window.KeyboardEvent('input', attributes); document.activeElement.dispatchEvent(e); e = new window.KeyboardEvent('change', attributes); document.activeElement.dispatchEvent(e); e = new window.KeyboardEvent('keyup', attributes); document.activeElement.dispatchEvent(e); }, 4); setTimeout(function() { var e = new window.KeyboardEvent('focus', attributes); document.dispatchEvent(e); e = new window.KeyboardEvent('keydown', attributes); document.dispatchEvent(e); e = new window.KeyboardEvent('beforeinput', attributes); document.dispatchEvent(e); e = new window.KeyboardEvent('keypress', attributes); document.dispatchEvent(e); e = new window.KeyboardEvent('input', attributes); document.dispatchEvent(e); e = new window.KeyboardEvent('change', attributes); document.dispatchEvent(e); e = new window.KeyboardEvent('keyup', attributes); document.dispatchEvent(e); }, 100); } else if (event.keyCode != 0) { console.log('we got a non-enter press...: :', event.key, ' keyCode:', event.keyCode, ' charCode:', event.charCode); } }); <h2>convert each enter to a tab in JavaScript... check console for output</h2> <h3>we dispatchEvents on the activeElement... and the global element as well</h3> <input type='text' id='firstInput' /> <input type='text' id='secondInput' /> <button type="button" onclick="document.getElementById('demo').innerHTML = Date()"> Click me to display Date and Time.</button> <p id="demo"></p>

一个非jquery版本,工作在webkit和gecko:

var keyboardEvent = document.createEvent('KeyboardEvent'); var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? 'initKeyboardEvent' : 'initKeyEvent'; keyboardEvent[initMethod]( 'keydown', // event type: keydown, keyup, keypress true, // bubbles true, // cancelable window, // view: should be window false, // ctrlKey false, // altKey false, // shiftKey false, // metaKey 40, // keyCode: unsigned long - the virtual key code, else 0 0, // charCode: unsigned long - the Unicode character associated with the depressed key, else 0 ); document.dispatchEvent(keyboardEvent);

在alex2k8的基础上,这里有一个修订版,可以在jQuery支持的所有浏览器中工作(问题是缺少jQuery.event的参数。触发器,在使用内部函数时很容易忘记它)。

// jQuery plugin. Called on a jQuery object, not directly.
jQuery.fn.simulateKeyPress = function (character) {
  // Internally calls jQuery.event.trigger with arguments (Event, data, elem).
  // That last argument, 'elem', is very important!
  jQuery(this).trigger({ type: 'keypress', which: character.charCodeAt(0) });
};

jQuery(function ($) {
  // Bind event handler
  $('body').keypress(function (e) {
    alert(String.fromCharCode(e.which));
    console.log(e);
  });
  // Simulate the key press
  $('body').simulateKeyPress('x');
});

您甚至可以更进一步,让它不仅模拟事件,而且实际插入字符(如果它是一个输入元素),但是在尝试这样做时,有许多跨浏览器的问题。最好使用更精致的插件,如SendKeys。

下面是一个在Chrome和Chromium上工作的解决方案(只测试了这些平台)。似乎Chrome有一些错误或自己的方法来处理关键代码,所以这个属性必须单独添加到KeyboardEvent。

函数simulateKeydown (keycode, istrl,isAlt,isShift){ var e = new KeyboardEvent("keydown",{冒泡泡:true, cancelable:true, char:String.fromCharCode(keycode), key:String.fromCharCode(keycode), shiftKey:isShift, ctrlKey:isCtrl, altKey:isAlt}); Object.defineProperty(e, 'keyCode', {get: function(){返回this.keyCodeVal;}}); e.keyCodeVal = keycode; document.dispatchEvent (e); } simulateKeydown(39, false, false, false);