我想要一个事件监听器,控制台在同时按下 ctrl + 左/右箭头键后记录文本字符串。但是,以下函数未拾取该事件:
$(document).keydown(function (event) {
if (event.which === 37 && event.ctrlKey) {
console.log('ctrl-left');
}
if (event.which === 39 && event.ctrlKey) {
console.log('ctrl-right');
}
else {
console.log('nothing detected');
}
});
知道我做错了什么吗?
最佳答案
您的 if 分支存在问题,按 CTRL+Left
按键会同时记录 ctrl-left
和 未检测到任何内容
同一时间。
此外,需要停止浏览器的默认事件处理以避免出现问题。
这对我在 Firefox 44.0.2 上有效:
$(document).keydown(function (event) {
event.preventDefault();
if (event.which === 37 && event.ctrlKey) {
console.log('ctrl-left');
} else if (event.which === 39 && event.ctrlKey) {
console.log('ctrl-right');
} else {
console.log('nothing detected');
}
});
关于javascript - 设置 ctrl + keydown 事件监听器时出现问题(未检测到),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35964842/