使用js檢測瀏覽器的實(shí)現(xiàn)代碼
在寫跨瀏覽器的js程序中,檢測瀏覽器是一個很重要的工作。我們不時要為不同的瀏覽器寫分支代碼。
如下是一種:
//添加事件工具函數(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;
}
}
1,第一種檢測瀏覽器方式稱為 user-agent 檢測方式。是最古老的,它檢測目標(biāo)瀏覽器的確切型號,包括瀏覽器的名稱和版本。其實(shí)就是一個字符串,用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;
}
2,第二種稱為 對象/特征 檢測方式,這是一種判斷瀏覽器能力的方式,也是目前流行的方式。即在使用一個對象之前檢測它是否存在。上面提到的addEvent方法中就使用了該方式。.addEventListener是w3c dom標(biāo)準(zhǔn)方式,而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 方式,即某些表現(xiàn)不是瀏覽器廠商刻意實(shí)現(xiàn)的。如下:
var isIE = !+"\v1";
var isIE = !-[1,];
var isIE = "\v"=="v";
isSafari=/a/.__proto__=='//';
isOpera=!!window.opera;
最經(jīng)典的莫過于 !-[1,] 的判斷方式,目前最少代碼判斷IE的方式,只需6個byte。這是個俄國人 發(fā)現(xiàn)的。利用了數(shù)組[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
}());
被稱為史上最有創(chuàng)意的IE判斷。
注1:isIE = "\v" == "v" 方式IE9已經(jīng)修復(fù)該bug,不能用此方式判斷IE瀏覽器了(2010-6-29用IE9 pre3測試的)
相關(guān)文章
Javascript學(xué)習(xí)筆記之 對象篇(三) : hasOwnProperty
判斷一個屬性是定義在對象本身而不是繼承自原型鏈,我們需要使用從 Object.prototype 繼承而來的 hasOwnProperty 方法。 hasOwnProperty 方法是 Javascript 中唯一一個處理對象屬性而不會往上遍歷原型鏈的。2014-06-06JavaScript中的prototype.bind()方法介紹
在JavaScript中,我們經(jīng)常用到函數(shù)綁定,而當(dāng)你需要在另一個函數(shù)中保持this上下文時,使用Function.prototype.bind()會很方便2014-04-04jquery中prop()方法和attr()方法的區(qū)別淺析
官方例舉的例子感覺和attr()差不多,也不知道有什么區(qū)別,既然有了prop()這個新方法,不可能沒用吧,那什么時候該用attr(),什么時候該用prop()呢2013-09-09