javascript獲取元素CSS樣式代碼示例
使用css控制頁面有4種方式,分別為行內樣式(內聯(lián)樣式)、內嵌式、鏈接式、導入式。
行內樣式(內聯(lián)樣式)即寫在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屬性僅僅代表了元素的內聯(lián)樣式,如果一個元素的部分樣式信息寫在內聯(lián)樣式中,一部分寫在外部的css文件中,通過style屬性是不能獲取到元素的完整樣式信息的。因此,需要使用元素的計算樣式才獲取元素的樣式信息。
用window對象的getComputedStyle方法來獲取一個元素的計算樣式,此方法有2個參數(shù),第一個參數(shù)為要獲取計算樣式的元素,第二個參數(shù)可以是null、空字符串、偽類(如:before,:after),這兩個參數(shù)都是必需的。
來個例子
<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以及更早的版本中沒有實現(xiàn),但是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屬性的真正用途所在)。
相關文章
JavaScript中關于indexOf的使用方法與問題小結
indexOf方法的作用是:根據(jù)給定參數(shù)x返回目標字符串(可以看成字符的數(shù)組)或數(shù)組中與x相等的項的索引。2010-08-08
JavaScript String.replace函數(shù)參數(shù)實例說明
JavaScript String.replace函數(shù)作用是將源自符串中的match替換為replacement并返回替換后的字符串,使用介紹如下,不會的朋友可以了解下哈2013-06-06

