Chrome移动仿真模式下的(maxTouchPoints)和(文档中的“ ontouchstart”)错误

时间:2019-04-24 15:10:27

标签: javascript google-chrome-devtools touch emulation

我使用像这样的触摸屏设备检测:

if (window.navigator.maxTouchPoints || 'ontouchstart' in document)  
    // handle as mobile device
else
    // handle as desktop

当我在Chrome移动仿真中更改屏幕时,maxTouchPoints'ontouchstart' in document的结果都是不可预测的。

对于一个相同的模拟屏幕,它可能返回maxTouchPoints等于0或1,而'ontouchstart' in document等于truefalse

所以,我真的不能检查这张纸。
您能推荐一种解决方法吗?

2 个答案:

答案 0 :(得分:1)

我创建了以下函数来检查触摸点是否实际启用(例如,使用设备/模拟器上的“启用触摸点按钮”):

function isTouchEventsEnabled() {
    // Bug in FireFox+Windows 10, navigator.maxTouchPoints is incorrect when script is running inside frame.
    // TBD: report to bugzilla.
    const navigator = (window.top || window).navigator;
    const maxTouchPoints = Number.isFinite(navigator.maxTouchPoints) ? navigator.maxTouchPoints : navigator.msMaxTouchPoints;
    if (Number.isFinite(maxTouchPoints)) {
        // Windows 10 system reports that it supports touch, even though it acutally doesn't (ignore msMaxTouchPoints === 256).
        return maxTouchPoints > 0 && maxTouchPoints !== 256;
    }
    return 'ontouchstart' in window;
}

答案 1 :(得分:0)

怎么样?

function isTouchscreen() {
  return ("ontouchstart" in window) || (navigator.MaxTouchPoints > 0) ? true : false;
}

if (isTouchscreen()) {
  console.log('IS touchscreen');}
else {
  console.log('IS NOT touchscreen');
}

参考:https://developer.mozilla.org/en-US/docs/Web/API/Navigator/maxTouchPoints