第一种检测浏览器方式称为 user-agent 检测方式。是最古老的,它检测目标浏览器的确切型号,包括浏览器的名称和版本。其实就是一个字符串,用 navigator.userAgen 或 navigator.appName 获取。如下:
2,
- function isIE(){
- return navigator.appName.indexOf("Microsoft Internet Explorer")!=-1 && document.all;
- }
- function isIE6() {
- return navigator.userAgent.split(";")[1].toLowerCase().indexOf("msie 6.0")=="-1"?false:true;
- }
- function isIE7(){
- return navigator.userAgent.split(";")[1].toLowerCase().indexOf("msie 7.0")=="-1"?false:true;
- }
- function isIE8(){
- return navigator.userAgent.split(";")[1].toLowerCase().indexOf("msie 8.0")=="-1"?false:true;
- }
- function isNN(){
- return navigator.userAgent.indexOf("Netscape")!=-1;
- }
- function isOpera(){
- return navigator.appName.indexOf("Opera")!=-1;
- }
- function isFF(){
- return navigator.userAgent.indexOf("Firefox")!=-1;
- }
- function isChrome(){
- return navigator.userAgent.indexOf("Chrome") > -1;
- }
第二种称为 对象 / 特征 检测方式,这是一种判断浏览器能力的方式,也是目前流行的方式。即在使用一个对象之前检测它是否存在。上面提到的 addEvent 方法中就使用了该方式。.addEventListener 是 w3c dom 标准方式,而 IE 使用自己特有 attachEvent。以下列举几个:
a,talbe.cells 只有 IE/Opera 支持。
b,innerText/insertAdjacenthtml 除 Firefox 外,IE6/7/8/Safari/Chrome/Opera 都支持。
c,window.external.AddFavorite 用来在 IE 下添加到收藏夹。
d,window.sidebar.addPanel 用来在 FF 下添加到收藏夹。
3,第三种很有趣,暂且称为 浏览器缺陷或 bug 方式,即某些表现不是浏览器厂商刻意实现的。如下:
- var isIE = !+"\v1";
- var isIE = !-[1,];
- var isIE = "\v"=="v";
- isSafari=/a/.__proto__=='//';
- isOpera=!!window.opera;
最经典的莫过于 !-[1,] 的判断方式,目前最少代码判断 IE 的方式,只需 6 个 byte。这是个俄国人 发现的。利用了数组 [1,] 的 length。还有来自英国的年轻 James Padolsey 利用 IE 条件注释
- 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
- }());
被称为史上最有创意的 IE 判断。
注 1:isIE = "\v" == "v" 方式 IE9 已经修复该 bug,不能用此方式判断 IE 浏览器了 (2010-6-29 用 IE9 pre3 测试的)
来源: