傳統一般都是采用user-agent的檢測方式,它檢測目標瀏覽器的確切型號,包括瀏覽器的名稱和版本。其實就是一個字符串,用navigator.userAgen或navigator.appName獲取。如下:
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。
//添加事件工具函數
function addEvent(el,type,handle){
if(el.addEventListener){//for standard browses
el.addEventListener(type,handle,false);
}else if(el.attachEvent){//for IE
el.attachEvent("on"+event,handle);
}else{//other
el["on"+type]=handle;
}
}
在舉幾個列子:
1、talbe.cells只有IE/Opera支持。
2、innerText/insertAdjacentHTML除Firefox外,IE6/7/8/Safari/Chrome/Opera都支持。
3、window.external.AddFavorite用來在IE下添加到收藏夾。
4、window.sidebar.addPanel用來在Firefox下添加到收藏夾。
還有一種有趣的檢測方式,暫且稱為“瀏覽器缺陷或bug”方式,即某些表現不是瀏覽器廠商刻意實現的。如下:
var isIE = !+"v1";
var isIE = !-[1,];
var isIE = "v"=="v";
isSafari=/a/.__PRoto__=='//';
isOpera=!!window.opera;
isIE = "v" == "v" 方式IE9已經修復該bug,不能用此方式判斷IE瀏覽器了(2010-6-29用IE9平臺預覽第三版測試的)
最經典的莫過于 !-[1,] 的判斷方式,僅僅用了6 bytes判定IE瀏覽器,創世界最短紀錄,這組代碼利用了數組[1,]的length。
IE瀏覽器檢測代碼:
// ----------------------------------------------------------
// 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) + ']><![endif]-->',
all[0]
);
return v > 4 ? v : undef;
})();
這個代碼的意圖就是.通過while循環.將條件編譯寫入到div即頁面中,然后直接取注釋下的這個元素,直到取不到就退出循環。這樣就獲得了IE的最終版本,如果不是IE那么就是undefined。
新聞熱點
疑難解答