使用js檢測瀏覽器的實現代碼

來源:互聯網
上載者:User

在寫跨瀏覽器的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 = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
        all[0]
    );
    return v > 4 ? v : undef
}());

被稱為史上最有創意的IE判斷。

注1:isIE = "\v" == "v" 方式IE9已經修複該bug,不能用此方式判斷IE瀏覽器了(2010-6-29用IE9 pre3測試的)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.