傳統(tǒng)一般都是采用user-agent的檢測(cè)方式,它檢測(cè)目標(biāo)瀏覽器的確切型號(hào),包括瀏覽器的名稱(chēng)和版本。其實(shí)就是一個(gè)字符串,用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;
}
目前比較流行的檢測(cè)方式則是通過(guò)“對(duì)象/特征”來(lái)判斷瀏覽器能力的方式。下面的addEvent代碼就是使用了該方式。.addEventListener是w3c dom標(biāo)準(zhǔn)方式,而IE使用自己特有attachEvent。
//添加事件工具函數(shù)
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;
}
}
在舉幾個(gè)列子:
1、talbe.cells只有IE/Opera支持。
2、innerText/insertAdjacentHTML除Firefox外,IE6/7/8/Safari/Chrome/Opera都支持。
3、window.external.AddFavorite用來(lái)在IE下添加到收藏夾。
4、window.sidebar.addPanel用來(lái)在Firefox下添加到收藏夾。
還有一種有趣的檢測(cè)方式,暫且稱(chēng)為“瀏覽器缺陷或bug”方式,即某些表現(xiàn)不是瀏覽器廠商刻意實(shí)現(xiàn)的。如下:
var isIE = !+"v1";
var isIE = !-[1,];
var isIE = "v"=="v";
isSafari=/a/.__PRoto__=='//';
isOpera=!!window.opera;
isIE = "v" == "v" 方式IE9已經(jīng)修復(fù)該bug,不能用此方式判斷IE瀏覽器了(2010-6-29用IE9平臺(tái)預(yù)覽第三版測(cè)試的)
最經(jīng)典的莫過(guò)于 !-[1,] 的判斷方式,僅僅用了6 bytes判定IE瀏覽器,創(chuàng)世界最短紀(jì)錄,這組代碼利用了數(shù)組[1,]的length。
IE瀏覽器檢測(cè)代碼:
// ----------------------------------------------------------
// 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;
})();
這個(gè)代碼的意圖就是.通過(guò)while循環(huán).將條件編譯寫(xiě)入到div即頁(yè)面中,然后直接取注釋下的這個(gè)元素,直到取不到就退出循環(huán)。這樣就獲得了IE的最終版本,如果不是IE那么就是undefined。
新聞熱點(diǎn)
疑難解答
圖片精選