我编写了一个jQuery插件,可以在桌面和移动设备上使用。我想知道是否有一种方法可以用JavaScript来检测设备是否具有触摸屏功能。我使用jquery-mobile.js来检测触摸屏事件,它适用于iOS, Android等,但我也想根据用户的设备是否有触摸屏来编写条件语句。
这可能吗?
我编写了一个jQuery插件,可以在桌面和移动设备上使用。我想知道是否有一种方法可以用JavaScript来检测设备是否具有触摸屏功能。我使用jquery-mobile.js来检测触摸屏事件,它适用于iOS, Android等,但我也想根据用户的设备是否有触摸屏来编写条件语句。
这可能吗?
当前回答
更新:在将整个功能检测库拉入你的项目之前,请阅读下面blmstr的回答。检测实际的触摸支持更加复杂,Modernizr只涵盖了一个基本的用例。
Modernizr是一种很棒的轻量级方法,可以在任何网站上进行各种特征检测。
它只是为每个特性在html元素中添加类。
然后你可以在CSS和JS中轻松地瞄准这些功能。例如:
html.touch div {
width: 480px;
}
html.no-touch div {
width: auto;
}
和Javascript (jQuery示例):
$('html.touch #popup').hide();
其他回答
我喜欢这个:
function isTouchDevice(){
return window.ontouchstart !== undefined;
}
alert(isTouchDevice());
许多这些工作,但要么需要jQuery,或javascript linters抱怨语法。考虑到你最初的问题要求“JavaScript”(不是jQuery,不是Modernizr)来解决这个问题,这里有一个简单的函数,每次都能工作。这也是你能得到的最小值。
function isTouchDevice() {
return !!window.ontouchstart;
}
console.log(isTouchDevice());
我要提到的最后一个好处是,该代码是框架和设备不可知的。享受吧!
jQuery v1.11.3
答案中有很多有用的信息。但是,最近我花了很多时间试图将所有事情结合到一个有效的解决方案中,以完成两件事:
检测正在使用的设备是触摸屏类型的设备。 检测设备被窃听。
除了这篇文章和用Javascript检测触摸屏设备,我发现Patrick Lauke的这篇文章非常有用:https://hacks.mozilla.org/2013/04/detecting-touch-its-the-why-not-the-how/
这是代码…
$(document).ready(function() {
//The page is "ready" and the document can be manipulated.
if (('ontouchstart' in window) || (navigator.maxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0))
{
//If the device is a touch capable device, then...
$(document).on("touchstart", "a", function() {
//Do something on tap.
});
}
else
{
null;
}
});
重要!*。On (events [, selector] [, data], handler)方法需要有一个选择器,通常是一个元素,它可以处理“touchstart”事件,或任何其他与触摸相关的类似事件。在本例中,它是超链接元素“a”。
现在,你不需要在JavaScript中处理常规的鼠标点击,因为你可以使用CSS来处理这些事件,使用超链接“a”元素的选择器,如下所示:
/* unvisited link */
a:link
{
}
/* visited link */
a:visited
{
}
/* mouse over link */
a:hover
{
}
/* selected link */
a:active
{
}
注意:还有其他的选择器…
这个即使在Windows Surface平板电脑上也能很好地工作!!
function detectTouchSupport {
msGesture = window.navigator && window.navigator.msPointerEnabled && window.MSGesture,
touchSupport = (( "ontouchstart" in window ) || msGesture || window.DocumentTouch && document instanceof DocumentTouch);
if(touchSupport) {
$("html").addClass("ci_touch");
}
else {
$("html").addClass("ci_no_touch");
}
}
jQuery扩展支持对象:
jQuery.support.touch = 'ontouchend' in document;
现在你可以在任何地方检查它,像这样:
if( jQuery.support.touch )
// do touch stuff