在對網頁進行調試的過程中,經常會用到js來獲取元素的CSS樣式,方法有很多很多,現在僅把我經常用的方法總結如:
1. obj.style:這個方法只能JS只能獲取寫在html標簽中的寫在style屬性中的值(style=”…”),而無法獲取定義在<style type="text/css">里面的屬性。
<html xmlns=”http://www.w3.org/1999/xhtml“> <head> <meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ /> <title>JS獲取CSS屬性值</title> <style type=”text/css”> <!– .ss{color:#cdcdcd;} –> </style> </head> <body> <div id=”css88″ class=”ss” style=”width:200px; height:200px; background:#333333″>JS獲取CSS屬性值</div> <script type=”text/javascript”> alert(document.getElementById(“css88″).style.width);//200px alert(document.getElementById(“css88″).style.color);//空白 </script> </body> </html>
2. IE中使用的是obj.currentStyle方法,而FF是用的是getComputedStyle 方法
“DOM2級樣式”增強了document.defaultView,提供了getComputedStyle()方法。這個方法接受兩個參數:要取得計算樣式的元素和一個偽元素字符串(例如“:after”)。如果不需要偽元素信息,第二個參數可以是null。getComputerStyle()方法返回一個CSSStyleDeclaration對象,其中包含當前元素的所有計算的樣式。
其語法為:document.defaultView.getComputedStyle('元素', '偽類');
以下面的HTML頁面為例:
<!DOCTYPE html> <html> <head> <title>計算元素樣式</title> <style> #myDiv { background-color:blue; width:100px; height:200px; } </style> </head> <body> <div id ="myDiv" style="background-color:red; border:1px solid black"></div> <script> var myDiv = document.getElementById("myDiv"); var computedStyle = document.defaultView.getComputedStyle(myDiv, null); alert(computedStyle.backgroundColor); //"red" alert(computedStyle.width); //"100px" alert(computedStyle.height); //"200px" alert(computedStyle.border); //在某些瀏覽器中是“1px solid black” </script> </body> </html>
邊框屬性可能也不會返回樣式表中實際的border規則(Opera會返回,但其它瀏覽器不會)。存在這個差別的原因是不同瀏覽器解釋綜合屬性的方式不同,因為設置這種屬性實際上會涉及很多其他的屬性。在設置border時,實際上是設置了四個邊的邊框寬度、顏色、樣式屬性。因此,即使computedStyle.border不會在所有瀏覽器中都返回值,但computedStyle.borderLeftWidth則會返回值。
需要注意的是,即使有些瀏覽器支持這種功能,但表示值的方式可能會有所區別。例如,Firefox和Safari會返回將所有顏色轉換成RGB格式。因此,即使getComputedStyle()方法時,最好多在幾種瀏覽器中測試一下。
IE不支持getComputedStyle()方法,但它有一種類似的概念。在IE中,每個具有style屬性的元素還有一個currentStyle屬性。這個屬性是CSSStyleDeclaration的實例,包含當前元素全部計算后的樣式。取得這些樣式的方法差不多,如下:
var myDiv = document.getElementById("myDiv"); var computedStyle = myDiv.currentStyle; alert(computedStyle.backgroundColor); //"red" alert(computedStyle.width); //"100px" alert(computedStyle.height); //"200px" alert(computedStyle.border); // IE9及以上會打印出來為空 IE8及以下是undefined
總結一下:通過document.defaultView.getComputedStyle()得到背景色,不同瀏覽器得到的不一樣,可能會返回將所有顏色轉換成RGB格式,也可能是顏色值。
IE通過currentStyle方法得到的顏色值沒有將顏色轉化成RGB格式。
參考地址:http://camnpr.com/archives/1193.html
http://www.zhangxinxu.com/wordpress/2012/05/getcomputedstyle-js-getpropertyvalue-currentstyle/