1. 程式人生 > >JavaScript中如何用原生的js獲取style樣式

JavaScript中如何用原生的js獲取style樣式

1. Element.style——只能獲取內聯樣式

該方法只能獲取到內聯樣式,而無法獲取到<style></style>和<link href="">中的樣式

例如:

<h1 onclick="getStyle(this)" style="color: red">測試</h1>
	function getStyle(obj){
		var color=obj.style.color;
		alert(color)
	}
但是當沒有內聯樣式時,則無法獲取到預設樣式,
	function getStyle(obj){
		var backgroundColor=obj.style.backgroundColor;
		alert(backgroudColor);//空白
		obj.style.backgroundC='blue';
		alert(backgroundColor);//空白
	}

2. getComputedStyle()——獲取最終樣式,包括內聯樣式,不支援IE6-8

語法:window.getComputedStyle("元素", "偽類");

當不需要偽類是,第二個引數可以設定為null

	function getStyle(obj){
		var color=window.getComputedStyle(obj,null).backgroundColor
		alert(color);//rbga(0,0,0,0)
	}

也可以使用document.defaultView.getComputedStyle("元素", "偽類");

3. Element.currentStyle——適用於IE,可獲取內聯樣式,返回最終樣式

	function getStyle(obj){
		var backgroundColor=obj.currentStyle.backgroundColor
		alert(backgroundColor);//rbg(0,0,0)
	}
4. getPropertyValue()——不支援駝峰格式,不支援IE6-8
	function getStyle(obj){
		var backgroundColor=window.getComputedStyle(obj,null).getPropertyValue('background-color')
		alert(backgroundColor);//rbga(0,0,0,0)
	}

5. getAttribute——支援駝峰樣式,與getPropertyValue()類似

為了相容IE6-8,可以使用下面的方式獲取樣式

	function getStyle(obj){
		if(window.currentStyle){
			style=window.currentStyle(obj,null);
		}else{
			style=window.getComputedStyle(obj,null)
		}
		return style;
	}