我尝试做的是运行一个选择测试框的脚本(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);
答案 0 :(得分:1)
检测事件处理程序是一种检测Alt-0的简单方法。您可能会考虑进行更复杂的检查,以确定是否在Alt和0之间按下了另一个键(即此代码会将Alt-1-0
视为Alt-0
或Ctrl-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>