What's the best way to detect a 'touch screen' device using JavaScript?

后端 未结 30 3000
花落未央
花落未央 2020-11-21 23:50

I\'ve written a jQuery plug-in that\'s for use on both desktop and mobile devices. I wondered if there is a way with JavaScript to detect if the device has touch screen capa

30条回答
  •  庸人自扰
    2020-11-22 00:28

    The practical answer seems to be one that considers the context:

    1) Public site (no login)
    Code the UI to work with both options together.

    2) Login site
    Capture whether a mouse-move occurred on the login form, and save this into a hidden input. The value is passed with the login credentials and added to the user's session, so it can be used for the duration of the session.

    Jquery to add to login page only:

    $('#istouch').val(1); // <-- value will be submitted with login form
    
    if (window.addEventListener) {
        window.addEventListener('mousemove', function mouseMoveListener(){
            // Update hidden input value to false, and stop listening
            $('#istouch').val(0); 
            window.removeEventListener('mousemove', mouseMoveListener);
        });
    } 
    

    (+1 to @Dave Burt and +1 to @Martin Lantzsch on their answers)

提交回复
热议问题