【问题标题】:jQuery - add hotkeys [duplicate]jQuery - 添加热键 [重复]
【发布时间】:2019-03-26 01:21:29
【问题描述】:
当我点击键盘上的“1”时,我使用此代码复制段落:
$(document).keypress(function (e) {
if (e.which == 49) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($('.one').children('p').text()).select();
document.execCommand("copy");
$temp.remove();
}
});
但我想添加真正的热键,例如 ctrl + alt + 1
【问题讨论】:
标签:
javascript
jquery
html
css
【解决方案1】:
您可以使用keydown 和keyup,如下所示。
下面的代码所做的是在keydown 上,它将对象keys 中该键的值设置为true。它还使用 if 语句来检查是否按下了这 3 个键。如果是这样,它会有所作为。
17、18 和 49 是 CtrlShift1
的
keycodes
var keys = {};
$(document).keydown(function(e) {
keys[e.which] = true;
if (keys[17] && keys[18] && keys[49]) { // Ctrl + Alt + 1 in that order
console.log("pressed");
}
});
$(document).keyup(function(e) {
delete keys[e.which];
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
【解决方案2】:
$(document).keydown(function(e) {
if (e.ctrlKey && e.altKey && e.which == 49) { // Ctrl + Alt + 1 in that order
console.log("pressed");
}
});
我喜欢这个你可以使用 shiftkey 如果你想e.shiftKey
【解决方案3】:
无论有没有 jQuery,你都可以很容易地做到这一点(我已经包含了这两个版本)。只要记住一旦你知道你对按键感兴趣就用 evt.preventDefault() 阻止默认行为,以防用户的浏览器有一个与你想要使用的热键匹配的热键。
这里是 jQuery 版本
$(document).keydown(function(evt) {
if (!evt.ctrlKey || !evt.altKey || evt.which < 48 || evt.which >57) {
return;
}
evt.preventDefault();
switch(evt.which) {
case 49:
console.log("hotkey 1");
return;
case 50:
console.log("hotkey 2");
return;
case 51:
console.log("hotkey 3");
return;
case 52:
console.log("hotkey 4");
return;
case 53:
console.log("hotkey 5");
return;
case 54:
console.log("hotkey 6");
return;
case 55:
console.log("hotkey 7");
return;
case 56:
console.log("hotkey 8");
return;
case 57:
console.log("hotkey 9");
return;
case 48:
console.log("hotkey 0");
return;
}
});
这里是原生js版本
window.addEventListener("keydown", function (evt) {
if(!evt.altKey || !evt.ctrlKey || evt.which < 48 || evt.which > 57) {
return;
}
evt.preventDefault();
switch(evt.which) {
case 49:
console.log("hotkey 1");
return;
case 50:
console.log("hotkey 2");
return;
case 51:
console.log("hotkey 3");
return;
case 52:
console.log("hotkey 4");
return;
case 53:
console.log("hotkey 5");
return;
case 54:
console.log("hotkey 6");
return;
case 55:
console.log("hotkey 7");
return;
case 56:
console.log("hotkey 8");
return;
case 57:
console.log("hotkey 9");
return;
case 48:
console.log("hotkey 0");
return;
}
}, false);