如何在javascript中检测快捷键[在我的情况下[ctrl + shift + k]]?就像,如果用户按下此键,我必须显示一个对话框.
med*_*oix 14
document.onkeydown = keydown;
function keydown(evt){
if (!evt) evt = event;
if (evt.ctrlKey && evt.altKey && evt.keyCode==115){ //CTRL+ALT+F4
alert("CTRL+ALT+F4");
}
else if (evt.shiftKey && evt.keyCode == 9){ //Shif+TAB
alert("Shift+TAB");
}
}
Run Code Online (Sandbox Code Playgroud)
Dominic发布的网址上的内容将为您提供密钥代码.
知道这是一个非常老的问题(13 年前),
但我在 2022 年分享了我的最佳答案,如果我在 13 年前分享它,我想它会被标记为解决方案
,所以这个答案基于代码 boxx
<!-- FOR THE DEMO -->
<div id="demoA"></div>
Run Code Online (Sandbox Code Playgroud)
var shortcut = {
// (A) SET SHORTCUT KEYS TO LISTEN TO
listen : null,
set : (listen) => {
// (A1) KEY SEQUENCE + FUNCTION TO RUN
shortcut.listen = listen;
// (A2) KEY PRESS LISTENERS
window.addEventListener("keydown", (evt) => {
shortcut.track(evt.key.toLowerCase(), true);
});
window.addEventListener("keyup", (evt) => {
shortcut.track(evt.key.toLowerCase(), false);
});
},
// (B) KEY PRESS SEQUENCE TRACKER
sequence : [],
track : (key, direction) => {
// (B1) PREVENT AUTO CLEANING
if (shortcut.junk != null) { clearTimeout(shortcut.junk); }
// (B2) KEY DOWN
if (direction) { if (!shortcut.sequence.includes(key)) {
shortcut.sequence.push(key);
}}
// (B3) KEY UP
else {
let idx = shortcut.sequence.indexOf(key);
if (idx != -1) { shortcut.sequence.splice(idx, 1); }
}
// (B4) HIT SHORTCUT?
if (shortcut.sequence.length != 0) {
let seq = shortcut.sequence.join("-");
if (shortcut.listen[seq]) {
shortcut.sequence = [];
shortcut.listen[seq]();
}
// (B5) PREVENT "STUCK SEQUENCE" WHEN USER LEAVES PAGE
// E.G. OPEN NEW TAB WHILE IN MIDDLE OF KEY PRESS SEQUENCE
else {
shortcut.junk = setTimeout(shortcut.clean, 600)
}
}
},
// (C) AUTO CLEANUP
junk : null,
clean : () => {
shortcut.junk = null;
shortcut.sequence = [];
}
};
window.addEventListener("DOMContentLoaded", () => {
shortcut.set({
"control-shift-k" : () => {// Use https://keycode.info/ to help you get the key name [*]
document.getElementById("demoA").innerHTML = "CONTROL SHIFT K IS PRESSED"//[*]
document.getElementById("demoA").style.color = "green";//[*]
document.getElementById("demoA").style.backgroundColor = "lightgreen";//[*]
}
});
});
document.onkeydown = function (e) {//remove this function if you dont want to block default action
// normalize event
e = e || window.event;
// detecting multiple keys, e.g: Ctrl + shift + k and block default action (in edge it duplicates tab)
if (e.ctrlKey && !e.altKey && e.shiftKey && e.keyCode === 75) {//75 means k [*]
// prevent default action
if (e.preventDefault) {
e.preventDefault();
}
// IE
e.returnValue = false;
}
};
//[*] represents you have to change the code line for your needs
Run Code Online (Sandbox Code Playgroud)
ctrl+shift+k(如果您不想这样做,可以删除)| 归档时间: |
|
| 查看次数: |
3014 次 |
| 最近记录: |