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


当前回答

只要用户按下有问题的键,你就可以存储对该even的引用,并将其用于任何HTML其他元素:

EnterKeyPressToEmulate<input class="lineEditInput" id="addr333_1" type="text" style="width:60%;right:0%;float:right" onkeydown="keyPressRecorder(event)"></input> TypeHereToEmulateKeyPress<input class="lineEditInput" id="addr333_2" type="text" style="width:60%;right:0%;float:right" onkeydown="triggerKeyPressOnNextSiblingFromWithinKeyPress(event)"> Itappears Here Too<input class="lineEditInput" id="addr333_3" type="text" style="width:60%;right:0%;float:right;" onkeydown="keyPressHandler(event)"> <script> var gZeroEvent; function keyPressRecorder(e) { gZeroEvent = e; } function triggerKeyPressOnNextSiblingFromWithinKeyPress(TTT) { if(typeof(gZeroEvent) != 'undefined') { TTT.currentTarget.nextElementSibling.dispatchEvent(gZeroEvent); keyPressHandler(TTT); } } function keyPressHandler(TTT) { if(typeof(gZeroEvent) != 'undefined') { TTT.currentTarget.value+= gZeroEvent.key; event.preventDefault(); event.stopPropagation(); } } </script>

如果你创建自己的事件,你可以设置keyCode,你可以从任何真实的键盘事件复制现有的参数(忽略目标,因为它的工作dispatchEvent)和:

ta = new KeyboardEvent('keypress',{ctrlKey:true,key:'Escape'})

其他回答

基于@aljgom的回答:

这对我来说很有效。而不是像aljgom建议的那样将事件分派给元素,而是将它分派给文档。

document.dispatchEvent(new KeyboardEvent("keydown", { key: "c" }));

一个非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);

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

铬测试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);
}

本地JavaScript与TypeScript支持的解决方案:

键入keyCode或您正在使用的任何属性,并将其转换为KeyboardEventInit

例子

const event = new KeyboardEvent("keydown", { 38岁的键码: } as KeyboardEventInit);

这对我来说是有效的,它确实为我的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>