使用JavaScript程序化按下Alt 0

3
我要做的是运行一个脚本(JS),选择一个测试框。它的ID字段名称是JMan。一旦选择了该字段,我正在尝试通过编程使我的代码执行按键组合ALT+0,然后延迟5秒。顺便说一下,我正在IE浏览器中执行此操作。
function myFunction() {
    var keyboardEvent = document.createEvent("keyboardEvent").;
    document.getElementById("JMan");
}
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, // viewArg: should be window
    false, // ctrlKeyArg
    true, // altKeyArgenter code here
    false, // shiftKeyArg
    false, // metaKeyArg
    48, // keyCodeArg : unsigned long the virtual key code, else 0
    0 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0
);
document.dispatchEvent(keyboardEvent);

1
Alt + 0 应该做什么? - deceze
一旦选择了JMan字段并启动ALT 0,它会打开另一个迷你窗口。如果有任何错误或者我在问一些显而易见的问题,请原谅,因为我是JS的新手,通常尝试使用Selenium来完成这个任务,但是该项目要求使用JS和IE。 - Black_1
1个回答

1
检测事件处理程序是一种简单的方法来检测Alt-0。您可能需要考虑更复杂的检查,以确定在Alt和0之间是否按下了其他键(即,此代码将把Alt-1-0视为Alt-0Ctrl-Alt-0视为Alt-0)(至少它检查您是否按住Alt-0)。这主要是因为不同浏览器之间的键盘事件差异很大,我希望制作出的东西能够在大多数情况下正常工作。
本示例中的按钮会触发一个最小的“Alt-0”事件,旨在供事件处理程序捕获(或者您应该能够在窗口中键入Alt-0)。

function fireAlt0() {
    console.log("firing event");
    window.dispatchEvent(new KeyboardEvent("keydown", { key: "0", altKey: true }));
}

function detectAlt0(event) {
    if ("keydown" == event.type) { // we might want to use the same function for any of ( keydown, keypress, keyup ) events
        if (event.key == "0" && event.altKey && !event.repeat) {
            console.log("Open a window!");
        }
    }
}
    
window.addEventListener("DOMContentLoaded", function () {
    // Use keydown because keypress won't fire for the Alt-0 combination (since it doesn't produce a visible character)
    window.addEventListener("keydown", detectAlt0, false);
    document.getElementById("button").addEventListener("click", fireAlt0, false);
}, false);
<button id="button">fireAlt0</button>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接