检测对给定 JavaScript 事件的支持?
我有兴趣使用 JavaScript hashchange 事件来监视 URL 片段标识符的更改。我知道 Really Simple History 以及相关的 jQuery 插件。然而,我得出的结论是,在我的特定项目中,并不值得额外增加另一个 JS 文件的开销。
我想做的是走“渐进增强”路线。也就是说,我想测试访问者的浏览器是否支持 hashchange 事件,并编写我的代码来使用它(如果可用),将其作为增强功能而不是核心功能。 IE 8、Firefox 3.6 和 Chrome 4.1.249 支持它,这约占我网站流量的 20%。
那么,呃...有什么方法可以测试浏览器是否支持特定事件?
I'm interested in using the JavaScript hashchange event to monitor changes in the URL's fragment identifier. I'm aware of Really Simple History and the jQuery plugins for this. However, I've reached the conclusion that in my particular project it's not really worth the added overhead of another JS file.
What I would like to do instead is take the "progressive enhancement" route. That is, I want to test whether the hashchange event is supported by the visitor's browser, and write my code to use it if it's available, as an enhancement rather than a core feature. IE 8, Firefox 3.6, and Chrome 4.1.249 support it, and that accounts for about 20% of my site's traffic.
So, uh ... is there some way to test whether a browser supports a particular event?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
好吧,最好的方法不是通过浏览器嗅探,Juriy Zaytsev (@kangax) 提出了一种非常有用的方法来检测事件支持:
用法:
此技术现在在一些库中使用,例如 jQuery。
在此处阅读更多信息:
Well, the best approach is not going through browser sniffing, Juriy Zaytsev (@kangax) made a really useful method for detecting event support:
Usage:
This technique is now used in some libraries like jQuery.
Read more here:
Mozilla 文档建议如下:这也适用于 IE8 和 Chrome 5 beta(我没有测试 Chrome 4.1),并且在 Opera 和 Safari 中正确失败。
编辑:我链接到的 Mozilla 页面不再包含任何建议。我也找不到任何其他包含事件检测建议的 Mozilla 文档。
The
Mozilla documentationsuggested the following:This works in IE8 and the Chrome 5 beta too (I didn't test Chrome 4.1), and correctly fails in Opera and Safari.
Edit: the Mozilla page I linked to no longer contains any suggestions. I can't find any other Mozilla docs containing suggestions for event detection either.
这是对CMS提供的答案的修改,它不包含另一个函数,我认为它可以工作:
Here is a modification of the answer provided by CMS, which doesn't contain a function in another, which I think would work:
我认为最简单的解决方案是对事件类进行
typeof
检查。例如:
typeof(InputEvent)
在 Chrome 中返回"function"
,在 Internet Explorer 中返回"undefined"
。I think the simplest solution is to just do a
typeof
check on the event class.For example:
typeof(InputEvent)
returns"function"
in Chrome and"undefined"
in Internet Explorer.