使用JavaScript检测“触摸屏”设备的最佳方法是什么? [英] What's the best way to detect a 'touch screen' device using JavaScript?

查看:95
本文介绍了使用JavaScript检测“触摸屏”设备的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个jQuery插件,可以在桌面设备和移动设备上使用。我想知道是否有一种方法可以检测设备是否具有触摸屏功能。我正在使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆