如何检查用户是否使用javascript触摸设备(智能手机)

Mel*_*ife 2 javascript html5 sensor orientation

我想构建一个简单的Web应用程序,可以判断用户是否触摸了手机(设备).不只是屏幕,而是所有设备.所以我弄清楚如何检查用户是否触摸屏幕而不是方向和运动传感器部分.所以我发现了这段代码:

if (window.DeviceOrientationEvent) { 
  var x = document.getElementById('1'); 
  var y = document.getElementById('2');
  var z = document.getElementById('3');
  window.addEventListener('deviceorientation', function(eventData) {
        // gamma is the left-to-right tilt in degrees
        console.log(eventData.gamma);
        x.innerHTML = eventData.gamma;
        // beta is the front-to-back tilt in degrees
        console.log(eventData.beta);
        y.innerHTML = eventData.beta;
        // alpha is the compass direction the device is facing in degrees
        console.log(eventData.alpha);
        z.innerHTML = eventData.alpha;
    }, false);
}
Run Code Online (Sandbox Code Playgroud)

它向我展示了许多快速变化的数据!但当我把手机放在我的桌子上时,它会不断更改数据,就像我移动我的设备一样.那么如何检查用户是否移动了手机/设备?如果你可以帮我解决你的代码和解释,甚至可以向我展示一个我可以欣赏它的网站,我真的无法理解它!在一个完美的世界:

if(user.touchDevice){alert("YOU TOUCHED PHONE!!!");}
Run Code Online (Sandbox Code Playgroud)

非常感谢!抱歉我的英文:)

Mār*_*ovs 6

您无法可靠地检测触摸设备.您可以检测浏览器功能,例如Touch Events API(可以在非触摸设备上的浏览器中启用)或通过使用媒体查询(小型设备几乎总是具有触摸屏)根据屏幕大小来假设触摸功能.

请阅读本文以获取详细说明和可能的解决方案:http: //www.stucox.com/blog/you-cant-detect-a-touchscreen/

这是Modernizr用来检测"touchevents"的代码:

if (('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) { 
    // Touch events are supported
}
Run Code Online (Sandbox Code Playgroud)

https://github.com/Modernizr/Modernizr/blob/master/feature-detects/touchevents.js

  • 这无法捕获运行 Edge 的 Surface 平板电脑 (2认同)