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

这可能吗?


当前回答

我喜欢这个:

function isTouchDevice(){
    return window.ontouchstart !== undefined;
}

alert(isTouchDevice());

其他回答

我们尝试了modernizr实现,但检测触摸事件不再一致(IE 10有触摸事件在windows桌面,IE 11工作,因为已经放弃触摸事件和添加指针api)。

所以我们决定优化网站作为一个触摸网站,只要我们不知道用户有什么输入类型。这比任何其他解决方案都更可靠。

我们的研究表明,大多数桌面用户在点击之前会将鼠标移到屏幕上,所以我们可以检测到他们,并在他们能够点击或悬停任何东西之前改变他们的行为。

这是我们代码的简化版本:

var isTouch = true;
window.addEventListener('mousemove', function mouseMoveDetector() {
    isTouch = false;
    window.removeEventListener('mousemove', mouseMoveDetector);
});

使用上面所有的注释,我已经组装了下面的代码,是为我的需要工作:

var isTouch = (('ontouchstart' in window) || (navigator.msMaxTouchPoints > 0));

我在iPad、Android(浏览器和Chrome)、黑莓Playbook、iPhone 4s、Windows Phone 8、IE 10、IE 8、IE 10(带触摸屏的Windows 8)、Opera、Chrome和Firefox上进行了测试。

它目前在Windows Phone 7上无法运行,我还没有找到针对该浏览器的解决方案。

希望有人觉得这有用。

如果你测试document.documentElement中支持touchstart,这就很简单了

var x = 'touchstart'在document.documentElement; console.log (x) //如果支持返回true //否则返回false

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

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

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

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