getComputedStyle與currentStyle獲取樣式(style/class)

大家都知道,用document.getElementById(‘element').style.xxx可以獲取元素的樣式信息,可是它獲取的只是DOM元素style屬性裏的樣式規則,對於通過class屬性引用的外部樣式表,就拿不到我們要的信息了。

DOM標準裏有個全局方法getComputedStyle,可以獲取到當前對象樣式規則信息,如:getComputedStyle(obj,null).paddingLeft,就能獲取到對象的左內邊距。但是事情還沒完,萬惡的IE不支持此方法,它有自己的一個實現方式,那就是currentStyle,不同於全局方法getComputedStyle,它是作爲DOM元素屬性存在的,如:obj.currentStyle.paddingLeft,在IE中就獲取到對象的左內邊距了,兼容性的寫法如下:

return window.getComputedStyle ? window.getComputedStyle(obj,null).paddingLeft : obj.currentStyle.paddingLeft; 

這樣,就能在IE及FF中返回對象的當前樣式信息了。

特別注意一點:如果要獲取當前對象的顏色信息,IE返回的是16進制的'#ffffff',而FF返回的是rgb(255,255,255)

用js的style屬性可以獲得html標籤的樣式,但是不能獲取非行間樣式。那麼怎麼用js獲取css的非行間樣式呢?在IE下可以用currentStyle,而在火狐下面我們需要用到getComputedStyle。下面是一個小示例:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>js用currentStyle和getComputedStyle獲取css樣式</title>
	<style>
		#gt{
			width:100px;
			height:100px;
			background-color: red;
		}
	</style>
</head>
<body>
	<div id="gt"></div>

	<!-- JS -->
	<script>
		function getStyle(obj,attr){
			if(obj.currentStyle){
				return obj.currentStyle[attr];
			}else{
				return getComputedStyle(obj,null)[attr];
			}
		}

		window.onload = function(){
			var Gt = document.getElementById('gt');
			alert(getStyle(Gt,'width'));
		}
	</script>
</body>
</html>

注意:文中IE指 IE 9以下版本。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章