如何可靠地确定浏览器是否支持鼠标悬停事件?

Luk*_*nis 8 javascript browser mobile browser-feature-detection

过去,检查鼠标是否存在的最佳方法是寻找触摸事件支持.但是,桌面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();
    });
});
Run Code Online (Sandbox Code Playgroud)

Ash*_*ain 5

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