javascript 擷取元素樣式必殺技

來源:互聯網
上載者:User

   這篇文章主要介紹了javascript 擷取元素樣式必殺技,需要的朋友可以參考下

  Javascript擷取CSS屬性值方法:getComputedStyle和currentStyle

  1 .對於元素的內聯CSS樣式(

  hello

  ),可以直接使用element.style.color來直接擷取css屬性的值;

  2. 但是對於外部定義的css樣式使用這種方式就無法擷取了,而且IE瀏覽器和其他標準瀏覽器(Firefox,Chrome,Opera,Safari)使用的方法不一樣,IE瀏覽器使用element.currentStyle,W3C標準瀏覽器使用getComputedStyle來擷取。

  1. IE擷取元素外部定義的CSS屬性值: element.currentStyle

  currentStyle對象返回了元素上的樣式表,但是style對象只返回通過style標籤屬性應用到元素的內嵌樣式。

  因此,通過currentStyle對象擷取的樣式值可能與通過style對象擷取的樣式值不同。

  例如,如果段落的color屬性值通過連結或內建樣式表設定為紅色( red ),而不是內嵌的話,對象.currentStyle.color 將返回正確的顏色,而對象style.color不能傳回值。但是,如果使用者指定了,currentStyle和STYLE對象都將傳回值 red。

  currentStyle對象反映了樣式表中的樣式優先順序。在 HTML 中此順序為:

  1) 內嵌樣式

  2) 樣式表規則

  3) HTML 標籤屬性

  4) HTML 標籤的內部定義

  2. W3C擷取元素外部定義的CSS屬性值: window.getComputedStyle(element, pseudoElt)

  element必選,HTML元素

  pseudoElt必選,擷取該元素的偽類樣式

   代碼如下:

  function getStyle(node, property){

  if (node.style[property]) {

  return node.style[property];

  }

  else if (node.currentStyle) {

  return node.currentStyle[property];

  }

  else if (document.defaultView && document.defaultView.getComputedStyle) {

  var style = document.defaultView.getComputedStyle(node, null);

  return style.getPropertyValue(property);

  }

  return null;

  }

        :更多精彩文章請關注幫客之家編程教程欄目。

聯繫我們

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