jquery uaMatch原始碼_jquery

來源:互聯網
上載者:User
複製代碼 代碼如下:

// Useragent RegExp
rwebkit = /(webkit)[ \/]([\w.]+)/,
ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
rmsie = /(msie) ([\w.]+)/,
rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,
// Keep a UserAgent string for use with jQuery.browser
userAgent = navigator.userAgent,

// For matching the engine and version of the browser
browserMatch,

// Use of jQuery.browser is frowned upon.
// More details: http://docs.jquery.com/Utilities/jQuery.browser
uaMatch: function( ua ) {
ua = ua.toLowerCase();

var match = rwebkit.exec( ua ) ||
ropera.exec( ua ) ||
rmsie.exec( ua ) ||
ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
[];

return { browser: match[1] || "", version: match[2] || "0" };
}
browserMatch = jQuery.uaMatch( userAgent );
if ( browserMatch.browser ) {
jQuery.browser[ browserMatch.browser ] = true;
jQuery.browser.version = browserMatch.version;
}

分析:瀏覽器之間的相容性問題,這個一個曆史遺留問題。痛苦的是,作為一個前端開發人員得為這個相容性問題買單。我們做開發時,往往要為每種瀏覽器作出局部的代碼調整才能在相應的瀏覽器中良好的運行。我所知道的方法有兩種:1.瀏覽器檢測;2.對象檢測。
  在jQuery 中只要用行uaMatch()這個函數。用到的關鍵點有:1.regExp.exec(str);2.navigator.userAgent;
  一,regExp.exec(str);用Regex來在字串中尋找,並返回一個數組,這個數組的0元素是整個正則匹配,1元素是第一個子匹配,2元素是第二個子匹配,如此類推。
  二,navigator.userAgent:是javascript BOM的重要的對象之一,它主要用來返回當前的瀏覽器和作業系統的資訊。
    例如:firefox的navigator.userAgetn 的字串:"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13"
       IE8的navigator.userAgetn的字串:"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)".
    從各個瀏覽器的Regex可知,第一個子匹配為瀏覽器的名字,第二個為版本。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.