如何检测 javascript 中的 shift + key down?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7479307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I detect shift + key down in javascript?
提问by Bart
Possible Duplicate:
How to catch enter keypress on textarea but not shift+enter?
How can I detect shift + key down in JavaScript?
如何在 JavaScript 中检测 shift + key down?
采纳答案by Adam Eberlin
var onkeydown = (function (ev) {
var key;
var isShift;
if (window.event) {
key = window.event.keyCode;
isShift = !!window.event.shiftKey; // typecast to boolean
} else {
key = ev.which;
isShift = !!ev.shiftKey;
}
if ( isShift ) {
switch (key) {
case 16: // ignore shift key
break;
default:
alert(key);
// do stuff here?
break;
}
}
});
回答by Niet the Dark Absol
event.shiftKey
is a boolean. true
if the Shift key is being pressed, false
if not. altKey
and ctrlKey
work the same way.
event.shiftKey
是一个布尔值。true
如果正在按下 Shift 键,false
如果没有。altKey
并ctrlKey
以同样的方式工作。
So basically you just need to detect the keydown as normal with onkeydown
, and check those properties as needed.
所以基本上你只需要像往常一样检测 keydown onkeydown
,并根据需要检查这些属性。