有没有办法检测 Alt 键被按在哪一侧(右或左)?

2024-05-07

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:

window.onload = function(){
  document.getElementById('id').onkeydown = function(){
    alert(window.event.altLeft);
  }
}

2015年答案

DOM3 添加了一个location键盘事件的属性 http://www.w3.org/TR/DOM-Level-3-Events/#events-KeyboardEvent-location(也可以看看MDN https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/location)(早期版本有一个keyLocation属性)它可以满足您的需求,并在所有主要浏览器的最新版本中实现。

Demo:

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>

2011年答案

不能。一般情况下,无法以跨浏览器的方式区分左右修饰键。这shiftLeft, shiftRight, ctrlLeft, ctrlRight, altLeft, altRight的属性window.event全部仅适用于 IE,其他浏览器中不存在等效项。

DOM3 添加了一个location键盘事件的属性 http://www.w3.org/TR/DOM-Level-3-Events/#events-KeyboardEvent-location(早期版本有一个keyLocation属性)但 Firefox 没有实现这一点。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

有没有办法检测 Alt 键被按在哪一侧(右或左)? 的相关文章

随机推荐