在 JS/jQuery 中绑定箭头键 [英] Binding arrow keys in JS/jQuery
问题描述
如何将函数绑定到 Javascript 和/或 jQuery 中的左右箭头键?我查看了 jQuery 的 js-hotkey 插件(包装了内置的绑定函数以添加一个参数来识别特定的键),但它似乎不支持箭头键.
How do I go about binding a function to left and right arrow keys in Javascript and/or jQuery? I looked at the js-hotkey plugin for jQuery (wraps the built-in bind function to add an argument to recognize specific keys), but it doesn't seem to support arrow keys.
推荐答案
document.onkeydown = function(e) {
switch(e.which) {
case 37: // left
break;
case 38: // up
break;
case 39: // right
break;
case 40: // down
break;
default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
};
如果需要支持IE8,函数体开头为e = e ||窗口事件;switch(e.which || e.keyCode) {
.
If you need to support IE8, start the function body as e = e || window.event; switch(e.which || e.keyCode) {
.
(2020 年编辑)
请注意,KeyboardEvent.which
现在已弃用.请参阅此示例使用KeyboardEvent.key
用于检测箭头键的更现代的解决方案.
(edit 2020)
Note that KeyboardEvent.which
is now deprecated. See this example using KeyboardEvent.key
for a more modern solution to detect arrow keys.
这篇关于在 JS/jQuery 中绑定箭头键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!