我目前正在尝试在基于网络的项目的菜单上实施快捷方式功能。我已经实现了单键或双键快捷键组合(如 F1 , CTRL + Q 等等)
$("#MyField").keydown(function (eventData) {
if (eventData.keyCode == 112) {
eventData.preventDefault();
myFunction_ToCall();
}
});
但现在我正朝着3键的组合方向前进,以访问sub-subMenu
,因为我的菜单看起来像这样:
Menu1
SubMenu2
SubMenue3
菜单2
因此,要访问 1. Sub-SubMenu1
,路径将类似于1. Menu1 > 1. SubMenu1 > 1. Sub-SubMenu1
,组合键将类似于 CTRL + < kbd> 1 + 1 + 1 `。
我搜索了很多,但找不到更好的解决方案。而现在我很困惑如何实现它。任何人都可以帮助我!!
答案 0 :(得分:2)
我会使用KeyboardEvent.key
,KeyboardEvent.ctrlKey
和一个树,每个键击序列形成一个分支:
step = shortcuts = {
"1": {
"1": sayHello,
"2": sayGoodbye
}
};
document.addEventListener("keydown", function (ev) {
if (ev.key === "Control") {
step = shortcuts; // go back to the root
ev.preventDefault();
}
});
document.addEventListener("keyup", function (ev) {
if (ev.ctrlKey && step[ev.key]) {
step = step[ev.key]; // a node was reached
if (typeof step === "function") {
step(); // a leaf was reached
}
}
});
function sayHello () {
console.log("Hello :-)");
}
function sayGoodbye () {
console.log("Goodbye :-(");
}
<p>Click here before trying shortcuts.</p>
以上代码段的改进版本:
step = shortcuts = {
"1": {
"1": "sayHello",
"2": "sayGoodbye"
}
};
commands = {
"sayHello": function () {
console.log("Hello :-)");
},
"sayGoodbye": function () {
console.log("Goodbye :-(");
}
};
printShortcuts(shortcuts, "CTRL");
document.addEventListener("keydown", function (ev) {
if (ev.key === "Control") {
step = shortcuts; // go back to the root
ev.preventDefault();
}
});
document.addEventListener("keyup", function (ev) {
if (ev.ctrlKey && step[ev.key]) {
step = step[ev.key]; // a node was reached
if (commands[step]) {
commands[step](); // a leaf was reached
}
}
});
function printShortcuts (node, prefix) {
if (typeof node === "string") {
document.body.innerHTML += prefix + " : " + node + "()<br>";
} else {
for (var child in node) {
printShortcuts(node[child], prefix + "-" + child);
}
}
}
<p>Click here before trying shortcuts.</p>
答案 1 :(得分:0)
来自Keyboard events with Ctrl, Alt, Shift keys
的这个示例怎么样?看看它如何捕捉组合......
function handleKeyDown(e) {
var ctrlPressed=0;
var altPressed=0;
var shiftPressed=0;
var evt = (e==null ? event:e);
shiftPressed=evt.shiftKey;
altPressed =evt.altKey;
ctrlPressed =evt.ctrlKey;
self.status=""
+ "shiftKey="+shiftPressed
+", altKey=" +altPressed
+", ctrlKey=" +ctrlPressed
if ((shiftPressed || altPressed || ctrlPressed)
&& (evt.keyCode<16 || evt.keyCode>18))
alert ("You pressed the "+fromKeyCode(evt.keyCode)
+" key (keyCode "+evt.keyCode+")\n"
+"together with the following keys:\n"
+ (shiftPressed ? "Shift ":"")
+ (altPressed ? "Alt " :"")
+ (ctrlPressed ? "Ctrl " :"")
)
return true;
}
document.onkeydown = handleKeyDown;