我编写了一个jQuery插件,可以在桌面和移动设备上使用。我想知道是否有一种方法可以用JavaScript来检测设备是否具有触摸屏功能。我使用jquery-mobile.js来检测触摸屏事件,它适用于iOS, Android等,但我也想根据用户的设备是否有触摸屏来编写条件语句。

这可能吗?


当前回答

由于Modernizr无法检测Windows Phone 8/WinRT上的IE10,一个简单的跨浏览器解决方案是:

var supportsTouch = 'ontouchstart' in window || navigator.msMaxTouchPoints;

你只需要检查一次,因为设备不会突然支持或不支持触摸,所以只需将它存储在一个变量中,这样你就可以更有效地多次使用它。

其他回答

虽然它只是alpha版本,但jquery移动框架值得一试。它将在移动浏览器中规范化这些类型的事件。也许可以看看他们在做什么。我假设jquery-mobile.js与这个框架有所不同。

有一种方法比检查他们是否拥有触摸屏更好,那就是检查他们是否正在使用触摸屏,而且这更容易检查。

if (window.addEventListener) {
    var once = false;
    window.addEventListener('touchstart', function(){
        if (!once) {
            once = true;
            // Do what you need for touch-screens only
        }
    });
}

实际的答案似乎是一个考虑上下文的答案:

1)公共站点(无法登录) 编写UI代码以同时使用这两个选项。

2)登录站点 捕获登录表单上是否发生了鼠标移动,并将其保存到隐藏的输入中。该值与登录凭据一起传递,并添加到用户的会话中,因此可以在会话期间使用它。

Jquery只添加到登录页面:

$('#istouch').val(1); // <-- value will be submitted with login form

if (window.addEventListener) {
    window.addEventListener('mousemove', function mouseMoveListener(){
        // Update hidden input value to false, and stop listening
        $('#istouch').val(0); 
        window.removeEventListener('mousemove', mouseMoveListener);
    });
} 

(@Dave Burt +1, @Martin Lantzsch +1)

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 
{

}

注意:还有其他的选择器…

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/);

我想会进行更彻底的检查。