Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
514 views
in Technique[技术] by (71.8m points)

javascript - Is there a way to detect which side the Alt key was pressed on (right or left)?

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?

This is how it works in IE for altLeft:

window.onload = function(){
  document.getElementById('id').onkeydown = function(){
    alert(window.event.altLeft);
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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 += "
" + message;
  e.preventDefault();
}, false);
<textarea id="ta" rows="10" cols="50">Click on here and press some modifier keys such as Shift</textarea>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...