在写跨浏览器的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;
}}
1,第一种检测浏览器方式称为 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;
}
2,第二种称为 对象/特征 检测方式,这是一种判断浏览器能力的方式,也是目前流行的方式。即在使用一个对象之前检测它是否存在。上面提到的addevent方法中就使用了该方式。.addeventlistener是w3c dom标准方式,而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 方式,即某些表现不是浏览器厂商刻意实现的。如下:
复制代码 代码如下:
var isie = !+\v1;
var isie = !-[1,];
var isie = \v==v;
issafari=/a/.__proto__=='//';
isopera=!!window.opera;
最经典的莫过于 !-[1,] 的判断方式,目前最少代码判断ie的方式,只需6个byte。这是个俄国人 发现的。利用了数组[1,]的length。还有来自英国的年轻 james padolsey 利用ie条件注释
复制代码 代码如下:
var ie = (function(){
var undef,
v = 3,
div = document.createelement('div'),
all = div.getelementsbytagname('i');
while (
div.innerhtml = '',
all[0]
);
return v > 4 ? v : undef
}());
被称为史上最有创意的ie判断。注1:isie = \v == v 方式ie9已经修复该bug,不能用此方式判断ie浏览器了(2010-6-29用ie9 pre3测试的)
