在写跨浏览器的js程序中,检测浏览器是一个很重要的工作。我们不时要为不同的浏览器写分支代码。如下是一种:
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; <wbr></wbr>
}
2,第二种称为<wbr><strong>对象/特征</strong><wbr>检测方式,这是一种判断浏览器能力的方式,也是目前流行的方式。即在使用 一个对象之前检测它是否存在。上面提到的addEvent方法中就使用了该方式。.addEventListener是w3c dom标准方式,而IE使用自己特有attachEvent。以下列举几个:</wbr></wbr>
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,第三种很有趣,暂且称为<wbr><strong>浏览器缺陷或bug<wbr></wbr></strong>方式,即某些表现不是浏览器厂商刻意实现的。如下:</wbr>
var isIE = !+"/v1";
var isIE = !-[1,];
var isIE = "/v"=="v";
isSafari=/a/.__proto__=='//';
isOpera=!!window.opera;
最经典的莫过于<wbr><strong>!-[1,]</strong><wbr>的判断方式,目前最少代码判断IE的方式,只需6个byte。这是个<a href="http://studioad.ru/blog/ie_detection_in_5_bytes/2010-01-08-103" target="_blank" style="text-decoration:none; color:rgb(144,80,50)">俄国人</a><wbr>发现的。利用了数组[1,]的length。</wbr></wbr></wbr>