Detecting that the browser has no mouse and is touch-only

前端 未结 24 1970
终归单人心
终归单人心 2020-11-27 09:35

I\'m developing a webapp (not a website with pages of interesting text) with a very different interface for touch (your finger hides the screen when you click) and mouse (re

24条回答
  •  攒了一身酷
    2020-11-27 10:13

    Just found a solution that I think is quite elegant.

    // flag as mouse interaction by default
    var isMouse = true;
    
    // detect a touch event start and flag it
    $(window).on('touchstart', function () {
      // if triggers touchstart, toggle flag
      // since touch events come before mouse event / click
      // callback of mouse event will get in callback
      // `isMouse === false`
      isMouse = false;
    });
    
    // now the code that you want to write
    // should also work with `mouse*` events
    $('a.someClass').on('click', function () {
      if (isMouse) {
        // interaction with mouse event
        // ...
      } else {
        // reset for the next event detection
        // this is crucial for devices that have both
        // touch screen and mouse
        isMouse = true;
    
        // interaction with touch event
        // ...
      }
    });
    

提交回复
热议问题