为了检测 IE,大多数 Javascript 库都会使用各种技巧。
- jQuery 似乎在页面的 DOM 中添加了一个临时对象来检测某些功能,
- YUI2 在其用户代理上执行正则表达式
YAHOO.env.ua = function()
(file yahoo.js
)
看完之后这个答案我认为这是真的,为了在 Javascript 中检测简单的 IE,我们可以简单地添加到我们的页面中:
<!--[if IE]><script type="text/javascript">window['isIE'] = true;</script><![endif]-->
<script type="text/javascript" src="all-your-other-scripts-here.js"></script>
Now the window.isIE
为我们所有的 Javascript 代码设置变量,只需执行以下操作:
if(window.isIE)
...
除了这可能会导致痛苦,因为它必须添加到所有页面中,有什么我可能不知道的问题/注意事项吗?
仅供参考:我知道使用更好对象检测而不是浏览器检测,但在某些情况下您仍然需要使用浏览器检测。
詹姆斯·帕多尔西放了一个GitHub 上的小片段我将在这里引用:
// ----------------------------------------------------------
// A short snippet for detecting versions of IE in JavaScript
// without resorting to user-agent sniffing
// ----------------------------------------------------------
// If you're not in IE (or IE version is less than 5) then:
// ie === undefined
// If you're in IE (>=5) then you can determine which version:
// ie === 7; // IE7
// Thus, to detect IE:
// if (ie) {}
// And to detect the version:
// ie === 6 // IE6
// ie > 7 // IE8, IE9 ...
// ie < 9 // Anything less than IE9
// ----------------------------------------------------------
// UPDATE: Now using Live NodeList idea from @jdalton
var ie = (function(){
var undef,
v = 3,
div = document.createElement('div'),
all = div.getElementsByTagName('i');
while (
div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
all[0]
);
return v > 4 ? v : undef;
}());
当然,所有的功劳都应该归功于詹姆斯,我只是信使(但如果我的复制粘贴操作出错,请射击信使)。
还要查看创建的分叉。保罗·爱尔兰 (Paul Irish) 在一篇文章中解释了内部运作方式comment.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)