8

过去,检查鼠标是否存在的最佳方法是寻找触摸事件支持。但是,桌面 Chrome 现在支持触摸事件,这使得该测试失败。

有没有办法直接测试鼠标悬停事件支持,而不是根据触摸事件的存在来推断它?

解决方案:根据 AshleysBrain 的回答,这是有效的代码。

jQuery(function()
{
    // Has mouse
    jQuery("body").one("mousemove", function(e)
    {
        attachMouseEvents();
    });

    // Has touchscreen
    jQuery("body").one("touchstart", function(e)
    {
        // Unbind the mouse detector, as this will fire on some touch devices. Touchstart should always fire first.
        jQuery("body").unbind("mousemove");

        attachTouchEvents();
    });
});
4

4 回答 4

5

您可以执行与检测键盘或触摸输入的解决方案相反的操作。只需等待实际的触摸事件或鼠标移动事件并据此做出决定。如果您检查事件处理程序的存在,浏览器可能会指示它有事件,即使它当前没有在支持它的硬件上运行,所以唯一可靠的做法是等待并查看哪些实际事件触发。

于 2012-02-28T08:36:44.180 回答
1

您可能想考虑使用Modernizr,您可以使用Modernizer.hasEvent()( docs ) 方法执行以下操作:

Modernizr.hasEvent("mouseover", document);
于 2012-02-24T09:24:54.400 回答
0

我试过这个,它的工作。

<html>
<head>
    <script type="text/javascript">
        function isEventSupported(eventName) {
            var el = document.createElement("body"[eventName] || "div");
            var isSupported = "on" + eventName.toLowerCase() in el || top.Event && typeof top.Event == "object" && eventName.toUpperCase() in top.Event;
            el = null;
            return isSupported;
        }
    </script>
</head>

<body onload="alert(isEventSupported('mouseover'));">TEST mouseover event</body>
</html>

isEventSupportedhttp://www.strictly-software.com/eventsupport.htm 获取了该功能

于 2012-02-28T09:41:54.847 回答
-1

如果网站可以像他们一样准确地检测到您正在使用移动浏览器,为什么您不能使用相同的技术来推断它们不支持鼠标悬停?

于 2012-02-24T09:11:44.207 回答