通過js獲取元素css樣式的方法
1.obj.style這個(gè)方法只能獲取寫在html標(biāo)簽的寫在style屬性中的值,而無法獲取定義在style type="text/css'中的屬性
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd“>
<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級(jí)樣式增強(qiáng)了document.defaultView,提供了getComputedStyle()方法
這個(gè)方法接受兩個(gè)參數(shù):要取得計(jì)算樣式的元素和一個(gè)偽元素字符串,例如:after.如果不需要偽元素,第二個(gè)參數(shù)可以是null,該方法將會(huì)返回一個(gè)CSSStyleDeclaration對(duì)象,其中包含當(dāng)前元素的所有計(jì)算樣式
<!DOCTYPE html>
<html>
<head>
<title>計(jì)算元素樣式</title>
<style>
#myDiv {
background-color:blue;
width:100px;
height:200px;
}
</style>
<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>
</head>
</html>
邊框?qū)傩钥赡芤膊粫?huì)返回樣式表中實(shí)際的border規(guī)則(Opera會(huì)返回密浑,但其它瀏覽器不會(huì))蛙婴。
存在這個(gè)差別的原因是不同瀏覽器解釋綜合屬性的方式不同尔破,因?yàn)樵O(shè)置這種屬性實(shí)際上會(huì)涉及很多其他的屬性。在設(shè)置border時(shí)懒构,實(shí)際上是設(shè)置了四個(gè)邊的邊框?qū)挾取㈩伾掌ⅰ邮綄傩允嵝恰R虼耍词筩omputedStyle.border不會(huì)在所有瀏覽器中都返回值冤灾,但computedStyle.borderLeftWidth則會(huì)返回值。
需要注意的是韵吨,即使有些瀏覽器支持這種功能,但表示值的方式可能會(huì)有所區(qū)別椿疗。例如漏峰,F(xiàn)irefox和Safari會(huì)返回將所有顏色轉(zhuǎn)換成RGB格式届榄。因此,即使getComputedStyle()方法時(shí)铝条,最好多在幾種瀏覽器中測試一下。