在寫跨瀏覽器的js程序中,檢測瀏覽器是一個很重要的工作。我們不時要為不同的瀏覽器寫分支代碼。
如下是一種:
復制代碼 代碼如下:
//添加事件工具函數
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;
}
}
復制代碼 代碼如下:
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;
}
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;
復制代碼 代碼如下:
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
}());
注1:isIE = "/v" == "v" 方式IE9已經修復該bug,不能用此方式判斷IE瀏覽器了(2010-6-29用IE9 pre3測試的)
新聞熱點
疑難解答
圖片精選