如何检测浏览器是否支持鼠标悬停事件? [英] How do I detect whether a browser supports mouseover events?

查看:489
本文介绍了如何检测浏览器是否支持鼠标悬停事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个网页,其中有一些onmouseover javascript行为,用于放置菜单(或类似的东西)。



显然,这不起作用在iPad或智能手机等触摸设备上。



如何检测浏览器是否支持悬停事件,如onmouseover或onmouseout以及CSS中的悬停伪标签?

注意:我知道如果我担心这个问题,我应该用另一种方式写,但我很好奇是否可以检测



编辑:当我说支持悬停事件时,我的意思是,浏览器是否有一个有意义的悬停表示事件。如果硬件支持它,但软件不支持(反之亦然),则没有意义的表示。除了一些即将推出的技术,我不认为任何触控设备都有悬浮事件的有意义的表示形式。

解决方案

  var supportsTouch =(typeof Touch ==object); 

只需检测它是否是触摸设备,然后执行您的特殊操作即可。
这是最简单的方法,因为大多数触摸设备模拟鼠标事件,但没有鼠标驱动的设备模拟触摸事件。



更新:考虑现在有多少设备现在有一天,并且约翰的评论我推荐使用 Modernizr


Let's assume I have a web page which has some onmouseover javascript behaviour to drop down a menu (or something similar)

Obviously, this isn't going to work on a touch device like the iPad or smartphones.

How can I detect whether the browser supports hover events like onmouseover or onmouseout and the :hover pseudotag in CSS?

Note: I know that if I'm concerned about this I should write it a different way, but I'm curious as to whether detection can be done.

Edit: When I say, "supports hover events", I really mean, "does the browser have a meaningful representation of hover events". If the hardware supports it but the software doesn't (or vice versa), there's no meaningful representation. With the exception of some upcoming tech, I don't think any touch devices have a meaningful representation of a hover event.

解决方案

var supportsTouch = (typeof Touch == "object");

Just detect if it's a touch device and then do your special stuff. This is the simplest approach since most touch devices emulate mouse events but no mouse driven device emulates touch events.

Update: Considering how many devices there are now a days and Johan's comments I'd recommend simply using Modernizr.

这篇关于如何检测浏览器是否支持鼠标悬停事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆