简体   繁体   中英

How can I reliably determine if a browser supports mouse-over events?

In the past, the best method to check for the presence of a mouse was to look for touch event support . However, desktop Chrome now supports touch events, making this test misfire.

Is there a way to test directly for mouseover event support, rather than inferring it based on the presence of touch events?

Resolution: Here is the code that worked, based on the answer from 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();
    });
});

You could do the opposite of the solution for detecting keyboard or touch input . Just wait for an actual touch event or mouse move event and decide based off that. If you check the presence of an event handler, the browser may indicate it has the event even if it is not currently running on hardware that supports it, so the only reliable thing to do is wait and see which actual events fire.

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

Modernizr.hasEvent("mouseover", document);

I have try this and it's work.

<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>

I took the function isEventSupported from http://www.strictly-software.com/eventsupport.htm

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM