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

前端 未结 4 1657
不知归路
不知归路 2020-11-30 09:41

Mostly this is a sanity check. The key code for both shift keys is 16. Does that mean it is actually impossible to distinguish a left and right shift events in a browser?

相关标签:
4条回答
  • 2020-11-30 10:14

    Internet explorer is capable of distinguishing left and right shift with the shiftLeft property:

    shiftLeft property (event)

    Otherwise, they are indistinguishable.

    0 讨论(0)
  • 2020-11-30 10:20

    The easiest way to do it

    $(document).ready(function(){
      $("html").keydown(function(e) {
    
          if (e.shiftKey) {
             if (event.location == 1) console.log('left shift');
             if (event.location == 2) console.log('right shift');
          }
    
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    Note: You have to click the inside white space when you run code snippet to activate keyboard keys. This is tested in Chrome and Safari.

    0 讨论(0)
  • 2020-11-30 10:21

    In newer browsers supporting DOM3 you can use event.location to check the location.

    In the DOM3 spec, there are 4 constants defined for location, DOM_KEY_LOCATION_STANDARD, DOM_KEY_LOCATION_LEFT, DOM_KEY_LOCATION_RIGHT, andDOM_KEY_LOCATION_NUMPAD.

    In this case, you can do:

    if (event.location === KeyboardEvent.DOM_KEY_LOCATION_LEFT){
    
    } else if (event.location === KeyboardEvent.DOM_KEY_LOCATION_RIGHT){
    
    }
    
    0 讨论(0)
  • 2020-11-30 10:31

    You can use event.code (the physical keyboard string) instead of event.key (the numeric ascii value).

    event.code MDN docs

    The KeyboardEvent.code property represents a physical key on the keyboard (as opposed to the character generated by pressing the key).

    If you scroll down to "Code values" at the bottom, you can find the two distinct shift keys:

    "ShiftLeft", "ShiftRight"

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