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
564 views
in Technique[技术] by (71.8m points)

javascript - Detect Alt Gr (Alt Graph) modifier on key press

In the javascript Event object, there are some boolean values to check if modifier keys are pressed:

  • ctrlKey: CTRL key.
  • altKey: ALT key.
  • altLeft: ALT left key. Only for IE.
  • altGraphKey: ALTGR key. Only for Chrome/Safari.

However, there are some issues:

  • IE and Chrome set ctrlKey to true and altKey to true when you press the ALTGR modifier.
  • Firefox sets ctrlKey to false and altKey to true when you press the ALTGR modifier, as only ALT has been pressed.
  • Chrome has the altGraphKey property, but it is always undefined.

Question: how can I difference between an ALT+CTRL or an ALTGR key press? Specially in Chrome.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The altGraphKey in webkit browsers no longer appears to exist (as at September 2013) and the behaviour of Firefox has changed. Browser behaviours for the AltGr key currently appear to be:

  • Webkit (Chrome) - ctrlKey: true, altKey: true
  • IE 8 - ctrlKey: false, altKey: true
  • IE 10 - ctrlKey: true, altKey: true
  • Mozilla (Firefox) - ctrlKey: true, altKey: true

Which is to say, they are all currently consistent (apart from IE8, which remains consistently inconsistent).

The following snippet should catch Alt Gr - but not Alt or Ctrl - in modern browsers. You will need a special case for IE8 however:

if (event.ctrlKey && event.altKey) {
    // Appears to be Alt Gr
}

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

...