有没有办法检测按下Alt键的哪一侧(右侧或左侧)? [英] Is there a way to detect which side the Alt key was pressed on (right or left)?
问题描述
有没有办法可以检测 Alt 键被按下哪一侧,即区分左或右 Alt ?我在某个地方看到IE可以使用 altLeft
和 altRight
属性 Event
对象。如果这是正确的,我们如何在Firefox中使用JavaScript检测它?
Is there a way that we can detect which side the Alt key was pressed on, i.e. distinguish between left or right Alt? I saw somewhere that it's possible with IE with the altLeft
and altRight
properties of the Event
object. If that is correct, how can we detect it in Firefox with JavaScript?
这是它在IE中的工作原理 altLeft
:
This is how it works in IE for altLeft
:
window.onload = function(){
document.getElementById('id').onkeydown = function(){
alert(window.event.altLeft);
}
}
推荐答案
2015回答
DOM3添加了 location
键盘事件的属性(另请参阅 MDN )(早期版本有一个 keyLocation
属性),它可以做你想要的并在所有主流浏览器的最新版本中实现。
2015 answer
DOM3 added a location
property of keyboard events (see also MDN) (earlier versions had a keyLocation
property instead) which does what you want and is implemented in recent versions of all major browsers.
演示:
document.getElementById("ta").addEventListener("keydown", function(e) {
var keyLocation = ["Standard", "Left", "Right", "Numpad", "Mobile", "Joystick"][e.location];
var message = "Key '" + (e.key || e.keyIdentifier || e.keyCode) + "' is down. Location: " + keyLocation;
this.value += "\n" + message;
e.preventDefault();
}, false);
<textarea id="ta" rows="10" cols="50">Click on here and press some modifier keys such as Shift</textarea>
不可以。通常,不可能以跨浏览器的方式区分左右修饰键。 shiftLeft
, shiftRight
, ctrlLeft
, ctrlRight
, altLeft
, altRight
的属性window.event
仅限IE,其他浏览器中不存在等效项。
No. In general, it is impossible to distinguish between left and right modifier keys in a cross-browser way. The shiftLeft
, shiftRight
, ctrlLeft
, ctrlRight
, altLeft
, altRight
properties of window.event
are all IE only and no equivalent exists in other browsers.
DOM3添加了 location
键盘事件的属性(早期版本有一个 keyLocation
属性)但Firefox没有实现这个。
DOM3 added a location
property of keyboard events (earlier versions had a keyLocation
property instead) but Firefox does not implement this.
这篇关于有没有办法检测按下Alt键的哪一侧(右侧或左侧)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!