用JavaScript判斷CSS瀏覽器類型首碼的兩種方法,javascriptcss

來源:互聯網
上載者:User

用JavaScript判斷CSS瀏覽器類型首碼的兩種方法,javascriptcss

不管我們對瀏覽器類型首碼有多麼的討厭,我們都不得不每天面對它,否者有些東西不能正常工作。這些首碼的用法有兩種:在CSS裡(例如“-moz-”)和在JS裡。有一個神奇的 X-Tag 項目裡有一段很聰明的JavaScript指令碼,可以用來判斷當前使用的是什麼首碼——讓我來展示它是如何工作的!

比如 CSS 首碼,IE 的是 "-ms-",舊版 Opera 的是 "-o-",Firefox 的是 "-moz-",Safari/Chrome 是 "-webkit-"。JavaScript 有多種方式判斷它們。

方法1: 特性判斷

// 取瀏覽器的 CSS 首碼var prefix = function() {  var div = document.createElement('div');  var cssText = '-webkit-transition:all .1s; -moz-transition:all .1s; -o-transition:all .1s; -ms-transition:all .1s; transition:all .1s;';  div.style.cssText = cssText;  var style = div.style;  if (style.webkitTransition) {    return '-webkit-';  }  if (style.MozTransition) {    return '-moz-';  }  if (style.oTransition) {    return '-o-';  }  if (style.msTransition) {    return '-ms-';  }  return '';}();

通過建立一個div,給其分別添加 -webkit-、-moz-、-o-、-ms- 的首碼 css 樣式,然後擷取 style,通過 style.xxxTransition 判斷是哪種首碼。

方法2: getComputedStyle 擷取 documentElement 所有樣式再解析

先通過 window.getComputedStyle 擷取 styles,將 styles 轉成數組

var styles = window.getComputedStyle(document.documentElement, '');var arr = [].slice.call(styles);console.log(arr);

Firefox arr 如下

Chrome arr 如下

能看到取到了具有各自瀏覽器自身實現的 CSS 首碼名稱。

把所有屬性串連成一個字串,然後用Regex匹配就能找出首碼了

// 取瀏覽器的 CSS 首碼var prefix = function() {  var styles = window.getComputedStyle(document.documentElement, '');  var core = (    Array.prototype.slice    .call(styles)    .join('')    .match(/-(moz|webkit|ms)-/) || (styles.OLink === '' && ['', 'o'])  )[1];  return '-' + core + '-';}();

 我們看到 方法2 比 方法1 代碼量少了許多。無論是方法1 和 方法2 ,都採用匿名函數一次性執行後返回結果,不需要每次判斷都調用一下函數。

以上內容就是小編通過兩種方法給大家介紹的用JavaScript判斷CSS瀏覽器類型首碼,希望大家喜歡。

聯繫我們

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