大多数情况下,这是一项健全性检查。两个shift键的关键代码是16.这是否意味着在浏览器中区分左右移位事件实际上是不可能的?
答案 0 :(得分:23)
在支持DOM3
的较新浏览器中,您可以使用event.location
来检查位置。
在the DOM3 spec中,为位置DOM_KEY_LOCATION_STANDARD
,DOM_KEY_LOCATION_LEFT
,DOM_KEY_LOCATION_RIGHT
和DOM_KEY_LOCATION_NUMPAD
定义了4个常量。
在这种情况下,你可以这样做:
if (event.location === KeyboardEvent.DOM_KEY_LOCATION_LEFT){
} else if (event.location === KeyboardEvent.DOM_KEY_LOCATION_RIGHT){
}
答案 1 :(得分:2)
答案 2 :(得分:2)
您可以使用event.code
(物理键盘字符串)代替event.key
(数字ascii值)。
KeyboardEvent.code属性表示键盘上的物理键(与按下键生成的字符相反)。
如果向下滚动至底部的“代码值”,则可以找到两个不同的移位键:
"ShiftLeft"
,"ShiftRight"
答案 3 :(得分:0)
最简单的方法
$(document).ready(function(){
$("html").keydown(function(e) {
if (e.shiftKey) {
if (event.location == 1) console.log('left shift');
if (event.location == 2) console.log('right shift');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
注意:运行代码段以激活键盘键时,必须单击内部空白区域。这是在Chrome和Safari中测试的。