我使用像这样的触摸屏设备检测:
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
等于true
或false
。
所以,我真的不能检查这张纸。
您能推荐一种解决方法吗?
答案 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