我编写了一个jQuery插件,可以在桌面和移动设备上使用.我想知道是否有一种方法可以检测设备是否具有触摸屏功能.我正在使用jquery-mobile.js来检测触摸屏事件,它可以在iOS,Android等上运行,但我也想根据用户的设备是否有触摸屏来编写条件语句.
那可能吗?
我正在开发一个webapp(不是一个有趣文本页面的网站),它有一个非常不同的触摸界面(当你点击时你的手指隐藏屏幕)和鼠标(严重依赖于悬停预览).如何检测到我的用户没有鼠标向他显示正确的界面?我计划为鼠标和触摸的人留下一个开关(就像一些笔记本电脑).
浏览器中的触摸事件功能实际上并不意味着用户正在使用触摸设备(例如,Modernizr不会剪切它).如果设备有鼠标,正确回答问题的代码应该返回false,否则返回true.对于具有鼠标和触摸功能的设备,它应该返回false(不是仅触摸)
作为旁注,我的触摸界面可能也适用于仅限键盘的设备,因此更多的是缺少我想要检测的鼠标.
为了使需求更加清晰,以下是我要实现的API:
// Level 1
// The current answers provide a way to do that.
hasTouch();
// Returns true if a mouse is expected.
// Note: as explained by the OP, this is not !hasTouch()
// I don't think we have this in the answers already, that why I offer a bounty
hasMouse();
// Level 2 (I don't think it's possible, but maybe I'm wrong, so why not asking)
// callback is called when the result of "hasTouch()" …我目前使用以下测试(取自Modernizr)来检测触摸支持:
function is_touch_device() {
    var bool;
    if(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
        bool = true;
    } else {
        injectElementWithStyles(['@media (',prefixes.join('touch-enabled),('),mod,')','{#modernizr{top:9px;position:absolute}}'].join(''), function(node) {
            bool = node.offsetTop === 9;
        });
    }
    return bool;
}
但有些设备是触摸和鼠标驱动的,所以我想要一个单独的功能来检测设备是否有鼠标支持.有什么好办法做这个检查?
最终我的意图是能够做到这些:
if(is_touch_device())
if(has_mouse_support())
if(is_touch_device() && has_mouse_support())