gpt4 book ai didi

javascript - 在 JS/jQuery 中绑定(bind)箭头键

转载 作者:IT老高 更新时间:2023-10-28 11:01:56 26 4
gpt4 key购买 nike

如何在 Javascript 和/或 jQuery 中将函数绑定(bind)到左右箭头键?我查看了 jQuery 的 js-hotkey 插件(包装了内置的绑定(bind)函数以添加参数以识别特定键),但它似乎不支持箭头键。

最佳答案

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) {.


(2020年编辑)
请注意,现在不推荐使用 KeyboardEvent.which。见 this example using KeyboardEvent.key用于检测箭头键的更现代的解决方案。

关于javascript - 在 JS/jQuery 中绑定(bind)箭头键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1402698/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com