Wil*_*ill 22 javascript progressive-enhancement javascript-events
我有兴趣使用JavaScript hashchange事件来监视URL片段标识符的更改.我知道Really Simple History和jQuery插件.但是,我得出结论,在我的特定项目中,另一个JS文件的额外开销并不值得.
我想做的是采取"渐进增强"的方式.也就是说,我想测试访问者的浏览器是否支持hashchange事件,并编写我的代码以便在可用时使用它,作为增强而不是核心功能.IE 8,Firefox 3.6和Chrome 4.1.249支持它,占我网站流量的20%左右.
那么,呃......有没有办法测试浏览器是否支持特定事件?
谢谢.
CMS*_*CMS 30
好吧,最好的方法是不通过浏览器嗅探,Juriy Zaytsev(@kangax)提供了一个非常有用的方法来检测事件支持:
var isEventSupported = (function(){
var TAGNAMES = {
'select':'input','change':'input',
'submit':'form','reset':'form',
'error':'img','load':'img','abort':'img'
}
function isEventSupported(eventName) {
var el = document.createElement(TAGNAMES[eventName] || 'div');
eventName = 'on' + eventName;
var isSupported = (eventName in el);
if (!isSupported) {
el.setAttribute(eventName, 'return;');
isSupported = typeof el[eventName] == 'function';
}
el = null;
return isSupported;
}
return isEventSupported;
})();
Run Code Online (Sandbox Code Playgroud)
用法:
if (isEventSupported('hashchange')) {
//...
}
Run Code Online (Sandbox Code Playgroud)
这种技术现在用在一些像jQuery这样的库中.
在这里阅读更多:
mer*_*tor 19
在Mozilla的文档提出以下建议:
if ("onhashchange" in window) {
alert("The browser supports the hashchange event!");
}
Run Code Online (Sandbox Code Playgroud)
这也适用于IE8和Chrome 5 beta(我没有测试Chrome 4.1),并且在Opera和Safari中正确失败.
| 归档时间: |
|
| 查看次数: |
11615 次 |
| 最近记录: |