完了,没看懂。。。试了下倒是很ok。。。

要想写出跨浏览器的javascript,就必须懂得嗅探技术。这是浏览器大战遗留下的大地雷,事已如此,只好认命,乖乖写分支结构吧,函数就是这样不知不觉中变长的。

先看单一浏览器的判断,我们没有必须去找navigator.userAgent的麻烦,我在国外的博客网站收集了如下hack,短小精悍:

 
ie = !+"/v1" ;
ie ='/v'=='v' ;
ie = 0//@cc_on+1;
ie = !!top.execScript;
ie = /*@cc_on!@*/!1;
ie8 = !!window.XDomainRequest;

//我自创的,如果是IE,会返回6,7,8代表ie6,ie7,ie8,否则返回1
IEVersion = (" " + (/*@cc_on @_jscript_version @*/-1)).slice(-1)

//基于条件编译的嗅探脚本,还有如下几个:
IE8=@cc_on @_jscript_version == 5.8 ? true : @false
IE7=@cc_on @_jscript_version == 5.7 ? true : @false
IE6=@cc_on @_jscript_version == 5.6 ? true : @false
IE55=@cc_on @_jscript_version == 5.5 ? true : @false


ff = /a/[-1]=='a';
ff3 = (function x(){})[-5]=='x';
ff2 = (function x(){})[-6]=='x';

safari=/a/.__proto__=='//';
safari = window.openDatabase;

chrome=/source/.test((/a/.toString+''));

opera=!!window.opera ;
opera=/^function (/.test([].sort);

还有判断maxthon的:

 
//出处:http://www.cnblogs.com/xiarugu/archive/2009/02/02/1382293.html
function IsMaxthon()
{
try{
window.external.max_invoke("GetHotKey");
return true;
}catch(ex){
return false;
}
}
alert(IsMaxthon());
 
//出处:http://bbs.maxthon.cn/archiver/?tid-148353.html
try{
if(external.max_version.indexOf("1.")==0){
var isMaxthon1 = 1;
}else{
var isMaxthon1 = 0;
}
}catch(e){
var isMaxthon1 = 0;
}

如果是想搞比较复杂的UI或者类库,对于浏览器的判断就要更严格一些,不能像上面那样游兵散勇。

 
B=(function x(){})[-5]=='x'?'FF3':(function x(){})[-6]=='x'?'FF2':/a/[-1]=='a'?'FF':'/v'=='v'?'IE':/a/.__proto__=='//'?'Saf':/s/.test(/a/.toString)?'Chr':/^function /(/.test([].sort)?'Op':'Unknown'

在Ext3的源码中能找出如下现整的嗅探脚本:

 
ua = navigator.userAgent.toLowerCase(),
check = function(r){
return r.test(ua);
},
isOpera = check(/opera/),
isChrome = check(/chrome/),
isWebKit = check(/webkit/),
isSafari = !isChrome && check(/safari/),
isSafari2 = isSafari && check(/applewebkit//4/), // unique to Safari 2
isSafari3 = isSafari && check(/version//3/),
isSafari4 = isSafari && check(/version//4/),
isIE = !isOpera && check(/msie/),
isIE7 = isIE && check(/msie 7/),
isIE8 = isIE && check(/msie 8/),
isIE6 = isIE && !isIE7 && !isIE8,
isGecko = !isWebKit && check(/gecko/),
isGecko2 = isGecko && check(/rv:1/.8/),
isGecko3 = isGecko && check(/rv:1/.9/),

好了,基本就是这样了,如果你有什么发现,也敬请拿出来分享一下!