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


当前回答

你可以使用dispatchEvent():

function simulateKeyPress() {
  var evt = document.createEvent("KeyboardEvent");
  evt.initKeyboardEvent("keypress", true, true, window,
                    0, 0, 0, 0,
                    0, "e".charCodeAt(0))
  var body = document.body;
  var canceled = !body.dispatchEvent(evt);
  if(canceled) {
    // A handler called preventDefault
    alert("canceled");
  } else {
    // None of the handlers called preventDefault
    alert("not canceled");
  }
}

我没有对此进行测试,但它改编自dispatchEvent()文档中的代码。您可能需要通读这些文档,以及createEvent()和initKeyEvent()的文档。

其他回答

js全屏切换方法的最佳方法:

function toggleFullScreen() {
      if (!document.fullscreenElement) {
        document.documentElement.requestFullscreen();
      } else if (document.exitFullscreen) {
        document.exitFullscreen();
      }
}

这对我来说是有效的,它确实为我的textaera模拟了一个按键。如果你想在整个页面中使用它,只需将KeySimulation()放在<body>上,就像这样<body onmousemove="KeySimulation()“>或如果不是onmousemove,那么onmouseover或onload也可以。

function KeySimulation() { var e = document.createEvent("KeyboardEvent"); if (e.initKeyboardEvent) { // Chrome, IE e.initKeyboardEvent("keyup", true, true, document.defaultView, "Enter", 0, "", false, ""); } else { // FireFox e.initKeyEvent("keyup", true, true, document.defaultView, false, false, false, false, 13, 0); } document.getElementById("MyTextArea").dispatchEvent(e); } <input type="button" onclick="KeySimulation();" value=" Key Simulation " /> <textarea id="MyTextArea" rows="15" cols="30"></textarea>

对于那些感兴趣的人,您可以可靠地重新创建键盘输入事件。为了更改输入区域中的文本(移动游标,或通过输入字符移动页面),必须严格遵循DOM事件模型:http://www.w3.org/TR/DOM-Level-3-Events/#h4_events-inputevents

该模型应该做到:

焦点(使用目标设置在DOM上分派)

然后对于每个字符:

keydown(在DOM上分派) Beforeinput(如果它是一个文本区域或输入,在目标分派) 按键(在DOM上分派) 输入(如果是文本区域或输入,则在目标处分派) 改变(如果它是一个选择,在目标分派) keyup(在DOM上分派)

然后,可选的大多数:

模糊(随目标设置在DOM上分派)

这实际上是通过javascript改变页面中的文本(不修改值语句),并适当地设置任何javascript侦听器/处理程序。如果你把顺序弄乱了,javascript就不会按适当的顺序触发,输入框中的文本不会改变,选择不会改变,或者光标不会移动到文本区域的下一个空格。

不幸的是,代码是为雇主写的,所以我不能分享它,但这绝对是可能的,但你必须以正确的顺序为每个元素重新创建整个关键输入“堆栈”。


编辑:我不是这个答案的原始海报,但我已经测试过了,我不能让它更新输入字段。下面是一个代码片段,其中的代码供其他人尝试或查看

let element = document.querySelector('input'); element.onkeydown = e => console.log('keydown on element: ' + e.key); document.onkeydown = e => console.log('keydown on document: ' + e.key + " " + e.target); dispatchButton.onclick = () => dispatchKey(element, 'a') dispatchKey = (target, key) => { let dom = document; // focus (dispatched on the DOM with the target set) let ev = new Event('focus', {target: target}); // this part seems to not work? when logging the // target in the onkeypress function it shows `document` instead of `input` // I also tried these and got the same behavior // ev.target = target; // and // Object.defineProperty(ev, 'target', {writable: false, value: target}); dom.dispatchEvent(ev); // keydown (dispatched on the DOM) dom.dispatchEvent(new KeyboardEvent('keydown', {'key': key, target: target})); // beforeinput (dispatched at the target if it's a textarea or input) target.dispatchEvent(new Event('beforeinput')); // keypress (dispatched on the DOM) dom.dispatchEvent(new KeyboardEvent('keypress', {'key': key})); // input (dispatched at the target if it's a textarea or input) target.dispatchEvent(new Event('input')); // change (dispatched at the target if it's a select) // keyup (dispatched on the DOM) dom.dispatchEvent(new KeyboardEvent('keyup', {'key': key})); // Then, optionally for most: // blur (dispatched on the DOM with the target set) dom.dispatchEvent(new Event('blur', {target: target})); console.log('dispatched'); } <input/> <button id="dispatchButton">Press to dispatch events </button>

这种方法支持跨浏览器更改键代码的值。 源

var $textBox = $("#myTextBox");

var press = jQuery.Event("keypress");
press.altGraphKey = false;
press.altKey = false;
press.bubbles = true;
press.cancelBubble = false;
press.cancelable = true;
press.charCode = 13;
press.clipboardData = undefined;
press.ctrlKey = false;
press.currentTarget = $textBox[0];
press.defaultPrevented = false;
press.detail = 0;
press.eventPhase = 2;
press.keyCode = 13;
press.keyIdentifier = "";
press.keyLocation = 0;
press.layerX = 0;
press.layerY = 0;
press.metaKey = false;
press.pageX = 0;
press.pageY = 0;
press.returnValue = true;
press.shiftKey = false;
press.srcElement = $textBox[0];
press.target = $textBox[0];
press.type = "keypress";
press.view = Window;
press.which = 13;

$textBox.trigger(press);

你可以用下面的代码模拟输入密码:

铬测试100%工作

DoCustomEvent('password', '#loginpin');



function DoCustomEvent(ct, elem){
var key;
var pressEvent = document.createEvent("CustomEvent");
pressEvent.initCustomEvent("keypress", true, false);

for (var i =0; i < ct.length; ++i)
{
    key                     = ct.charCodeAt(i);
    pressEvent.bubbles      = true;
    pressEvent.cancelBubble = false;
    pressEvent.returnValue  = true;
    pressEvent.key          = ct.charAt(i);
    pressEvent.keyCode      = key;
    pressEvent.which        = key;
    pressEvent.charCode     = key;
    pressEvent.shiftKey     = false;
    pressEvent.ctrlKey      = false;
    pressEvent.metaKey      = false;

    document.querySelector(elem).focus();

    //keypress //beforeinput //input //sendkeys //select
    setTimeout(function() {
        var e = new window.KeyboardEvent('keypress', pressEvent);
        document.activeElement.dispatchEvent(e);
        e = new window.KeyboardEvent('input', pressEvent);
        document.activeElement.dispatchEvent(e);

    }, 0);

    document.querySelector(elem).value = document.querySelector(elem).value + ct.charAt(i);
}