How can I tell if an event comes from right Ctrl key?

后端 未结 6 1718
慢半拍i
慢半拍i 2020-12-11 06:37

I have an event listener in Javascript, I can tell whether a key event is Ctrl (e.keyCode == 17), but how can I know this Ctrl comes from the right one or left

相关标签:
6条回答
  • 2020-12-11 07:01

    If you traced it you will find the same key is used for both (17) .. I think it is not possible to differentiate

    0 讨论(0)
  • 2020-12-11 07:08

    There is event.location property for left ctrl key it will be 1 for right one 2, you can check browser support on canIuse

    if (e.which == 17) {
       if (event.location == 1) {
          // left ctrl key
       } else if (event.location == 2) {
          // right ctrl key
       }
    }
    
    0 讨论(0)
  • 2020-12-11 07:09

    I don't think the keyCode is different.

    You can use e.ctrlKey for a better way to determine if the control key was pressed.

    It seems Flash can not tell which one is pressed either (either that or coded incorrectly).

    0 讨论(0)
  • 2020-12-11 07:09

    Just a quick note: I wouldn't base an architecture / design on the availability of the right control key - many laptop keyboards may not have two control keys.

    0 讨论(0)
  • 2020-12-11 07:13

    I don't know if it was available when this was asked, but you can distinguish left- from right-ctrl, as well as alt and shift. You can now use the KeyboardEvent.DOM_KEY_LOCATION_* properties to make this distinction.

    See Can javascript tell the difference between left and right shift key?

    Be aware though, I discovered that Chrome appears to have a defect in its implementation. See How can I distinguish left- and right- shift, ctrl, and alt keys onkeyup in Chrome with Javascript

    0 讨论(0)
  • 2020-12-11 07:16

    MSIE provides a ctrlLeftproperty on most events. The property values are:

    • true if the left key was pressed during the event
    • false if the left key was not pressed.

    You can combine event.ctrlKey and event.ctrlLeft to determine if the right Ctrl key was pressed:

    if (event.ctrlKey) {
        if (event.ctrlLeft) {
            // left Ctrl key pressed
        } else {
            // right Ctrl key pressed
        }
    } else {
        // no Ctrl key pressed
    }
    

    Note that the ctrlLeftproperty in a keyup is undefined because the Ctrl key is not pressed anymore.

    Tested under MSIE7 and MSIE9. Does not work under Firefox.

    See http://help.dottoro.com/ljqlvhuf.php for details.

    0 讨论(0)
提交回复
热议问题