使用css控制頁面有4種方式,分別為行內樣式(內嵌樣式)、內嵌式、連結式、匯入式。
行內樣式(內嵌樣式)即寫在html標籤中的style屬性中,如<div></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、空字串、偽類別(如: 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屬性的真正用途所在)。