使用 JavaScript 检测“触摸屏"设备的最佳方法是什么? [英] What's the best way to detect a 'touch screen' device using JavaScript?
问题描述
我编写了一个可在桌面和移动设备上使用的 jQuery 插件.我想知道是否有一种方法可以使用 JavaScript 来检测设备是否具有触摸屏功能.我正在使用 jquery-mobile.js 来检测触摸屏事件,它适用于 iOS、Android 等,但我还想根据用户的设备是否有触摸屏编写条件语句.
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 capability. I'm using jquery-mobile.js to detect the touch screen events and it works on iOS, Android etc., but I'd also like to write conditional statements based on whether the user's device has a touch screen.
这可能吗?
推荐答案
更新:请阅读blmstr的回答在将整个特征检测库拉入您的项目之前.检测实际触摸支持更为复杂,Modernizr 仅涵盖基本用例.
Update: Please read blmstr's answer below before pulling a whole feature detection library into your project. Detecting actual touch support is more complex, and Modernizr only covers a basic use case.
Modernizr 是一种出色的轻量级方法,可以在任何网站上进行各种特征检测.
Modernizr is a great, lightweight way to do all kinds of feature detection on any site.
它只是为每个功能的 html 元素添加类.
It simply adds classes to the html element for each feature.
然后您可以在 CSS 和 JS 中轻松定位这些功能.例如:
You can then target those features easily in CSS and JS. For example:
html.touch div {
width: 480px;
}
html.no-touch div {
width: auto;
}
和 Javascript(jQuery 示例):
And Javascript (jQuery example):
$('html.touch #popup').hide();
这篇关于使用 JavaScript 检测“触摸屏"设备的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!