javascript擷取元素CSS樣式程式碼範例

來源:互聯網
上載者:User


使用css控制頁面有4種方式,分別為行內樣式(內聯樣式)、內嵌式、連結式、匯入式。

行內樣式(內聯樣式)即寫在html標籤中的style屬性中,如<div style="width:100px;height:100px;"></div>

內嵌樣式即寫在style標籤中,例如<style type="text/css">div{width:100px; height:100px}</style>

連結式即為用link標籤引入css檔案,例如<link href="test.css" type="text/css" rel="stylesheet" />

匯入式即為用import引入css檔案,例如@import url("test.css")


如果想用javascript擷取一個元素的樣式資訊,首先想到的應該是元素的style屬性。但是元素的style屬性僅僅代表了元素的內聯樣式,如果一個元素的部分樣式資訊寫在內聯樣式中,一部分寫在外部的css檔案中,通過style屬性是不能擷取到元素的完整樣式資訊的。因此,需要使用元素的計算樣式才擷取元素的樣式資訊。

用window對象的getComputedStyle方法來擷取一個元素的計算樣式,此方法有2個參數,第一個參數為要擷取計算樣式的元素,第二個參數可以是null、Null 字元串、偽類(如:before,:after),這兩個參數都是必需的。

來個例子

<style type="text/css">

#testDiv{

  border:1px solid red;

  width: 100px;

  height: 100px;

  color: red;

}

</style>

<div id="testDiv"></div>

var testDiv = document.getElementById("testDiv");

var computedStyle = window.getComputedStyle(testDiv, "");

var width = computedStyle.width;  //100px

var height = computedStyle.height;  //100px

var color = computedStyle.color;  //rgb(255, 0, 0)
[/code]

註:擷取到的顏色屬性都是以rgb(#,#,#)格式返回的。

這個時候如果用testDiv.style來擷取樣式資訊,如testDiv.style.width肯定是為空白的。

 

getComputedStyle方法在IE8以及更早的版本中沒有實現,但是IE中每個元素有自己的currentStyle屬性。

so,來個通用的

複製代碼 代碼如下:
var testDiv = document.getElementById("testDiv");

var styleInfo = window.getComputedStyle ? window.getComputedStyle(testDiv, "") : testDiv.currentStyle;

var width = styleInfo.width;  //100px;

var height = styleInfo.height;  //100px;

var color = styleInfo.color;  // rgb(255, 0, 0)

 

最後要注意一點,元素的計算樣式是唯讀,如果想設定元素樣式,還得用元素的style屬性(這個才是元素style屬性的真正用途所在)。

聯繫我們

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