Detect Alt Gr (Alt Graph) modifier on key press

前端 未结 4 1630
野的像风
野的像风 2020-12-17 10:03

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

  • ctrlKey: CTRL key.
相关标签:
4条回答
  • 2020-12-17 10:40

    Disclaimer: I don't have a keyboard that has this key, so I can't test myself, but the spec says that can use the key property. This may be a good solution if you only need to support browsers that implement it (at time of writing, only Safari doesn't). You can check if the value is "AltGraph".

    window.onkeydown = function (e) {
      if (e.key === 'AltGraph') {
        console.log(e.key);
      }
    };

    0 讨论(0)
  • 2020-12-17 10:48

    I guess the ALTGR key and CTRL+ALT key combo are the same thing and there is no way to make a difference in Javascript. Pressing ALTGR+e and CTRL+ALT+e are both producing the € (euro) symbol on my keyboard/language setup. There are pages online to check keycodes. Hope this helps.

    0 讨论(0)
  • 2020-12-17 10:55

    Worth mentioning is that it is possible to detect this in modern browser by checking the location of the alt key event.

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

    0 讨论(0)
  • 2020-12-17 10:57

    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
    }
    
    0 讨论(0)
提交回复
热议问题