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

前端 未结 24 2020
终归单人心
终归单人心 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:05

    @Wyatt's answer is great and gives us a lot to think about.

    On my case, I chose to listen for the first interaction, to only then set a behavior. So, even if the user has a mouse, I will treat as touch device if first interaction was a touch.

    Considering the given order in which events are processed:

    1. touchstart
    2. touchmove
    3. touchend
    4. mouseover
    5. mousemove
    6. mousedown
    7. mouseup
    8. click

    We can assume that if mouse event gets triggered before touch, it is a real mouse event, not an emulated one. Example (using jQuery):

    $(document).ready(function() {
        var $body = $('body');
        var detectMouse = function(e){
            if (e.type === 'mousedown') {
                alert('Mouse interaction!');
            }
            else if (e.type === 'touchstart') {
                alert('Touch interaction!');
            }
            // remove event bindings, so it only runs once
            $body.off('mousedown touchstart', detectMouse);
        }
        // attach both events to body
        $body.on('mousedown touchstart', detectMouse);
    });
    

    That worked for me

提交回复
热议问题