我编写了一个jQuery插件,可以在桌面和移动设备上使用。我想知道是否有一种方法可以用JavaScript来检测设备是否具有触摸屏功能。我使用jquery-mobile.js来检测触摸屏事件,它适用于iOS, Android等,但我也想根据用户的设备是否有触摸屏来编写条件语句。
这可能吗?
我编写了一个jQuery插件,可以在桌面和移动设备上使用。我想知道是否有一种方法可以用JavaScript来检测设备是否具有触摸屏功能。我使用jquery-mobile.js来检测触摸屏事件,它适用于iOS, Android等,但我也想根据用户的设备是否有触摸屏来编写条件语句。
这可能吗?
当前回答
var isTouchScreen = 'createTouch' in document;
or
var isTouchScreen = 'createTouch' in document || screen.width <= 699 ||
ua.match(/(iPhone|iPod|iPad)/) || ua.match(/BlackBerry/) ||
ua.match(/Android/);
我想会进行更彻底的检查。
其他回答
更新2021
要查看以前的答案,请查看历史记录。我决定从头开始,因为在保存历史的时候,它变得难以控制。
我最初的回答是,使用与Modernizr使用的相同功能可能是一个好主意,但这不再有效,因为他们删除了这个PR: https://github.com/Modernizr/Modernizr/pull/2432上的“touchevents”测试,因为这是一个令人困惑的主题。
话虽如此,这应该是一个相当好的检测浏览器是否具有“触摸功能”的方法:
function isTouchDevice() {
return (('ontouchstart' in window) ||
(navigator.maxTouchPoints > 0) ||
(navigator.msMaxTouchPoints > 0));
}
但是对于比我更聪明的人写过的更高级的用例,我建议阅读这些文章:
斯图·考克斯:你无法检测触摸屏 触摸检测:它是“为什么”,而不是“如何” Patrick H. Lauke的敏感演讲
我使用上面的代码片段来检测是否有触摸,所以我的iframe会在台式电脑上显示,而不是在触摸时显示。我注意到Android 4.0的Opera Mini在单独使用blmstr代码时仍然注册为非触摸设备。(有人知道为什么吗?)
我最终使用:
<script>
$(document).ready(function() {
var ua = navigator.userAgent;
function is_touch_device() {
try {
document.createEvent("TouchEvent");
return true;
} catch (e) {
return false;
}
}
if ((is_touch_device()) || ua.match(/(iPhone|iPod|iPad)/)
|| ua.match(/BlackBerry/) || ua.match(/Android/)) {
// Touch browser
} else {
// Lightbox code
}
});
</script>
如果你测试document.documentElement中支持touchstart,这就很简单了
var x = 'touchstart'在document.documentElement; console.log (x) //如果支持返回true //否则返回false
所有浏览器支持,除了Firefox桌面始终为TRUE,因为Firefox桌面支持响应式设计的开发人员,即使你点击触摸按钮或不!
我希望Mozilla在下一个版本中解决这个问题。
我用的是火狐28桌面版。
function isTouch()
{
return !!("ontouchstart" in window) || !!(navigator.msMaxTouchPoints);
}
有一种方法比检查他们是否拥有触摸屏更好,那就是检查他们是否正在使用触摸屏,而且这更容易检查。
if (window.addEventListener) {
var once = false;
window.addEventListener('touchstart', function(){
if (!once) {
once = true;
// Do what you need for touch-screens only
}
});
}