过去,检查是否存在鼠标的最佳方法是查找touch event support。 .但是,桌面版 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();
});
});
最佳答案
您可以对 detecting keyboard or touch input 执行与解决方案相反的操作.只需等待实际的触摸事件或鼠标移动事件并根据它来决定。如果您检查事件处理程序的存在,浏览器可能会指示它有事件,即使它当前没有在支持它的硬件上运行,所以唯一可靠的做法是等待,看看触发了哪些实际事件。
关于javascript - 如何可靠地确定浏览器是否支持鼠标悬停事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9428064/