js獲取css樣式

css樣式分爲以下三種:

1、內聯樣式(在HTML元素的內部,又稱行內樣式)。

2、內部樣式(位於<head>標籤內部)。

3、外部樣式(通過link標籤引入)。

通過javascript獲取元素內聯樣式可以直接通過elementobj.style.prop即可獲取。

如果要獲取內部樣式或外部樣式上面那種方法就失效了,做法如下:

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

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

按例代碼如下:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>body換膚</title>
		<style type="text/css">
			*{margin: 0px;padding: 0px;}
			ul{list-style: none;}
			.myul1 li{display: inline-block;width: 30px;height: 20px;font-size: 0px;cursor: pointer;}
			.myul1 li:first-child{background-color: #f00;}
			.myul1 li:nth-child(2){background-color: #0f0;}
			.myul1 li:nth-child(3){background-color: #00f;}
		</style>
	</head>
	<body>
		<ul class="myul1" id="myul1">
			<li>紅色</li>
			<li>綠色</li>
			<li>藍色</li>
		</ul>
		<script type="text/javascript">
			var ali=document.getElementById('myul1').getElementsByTagName('li');
			for(var i=0;i<ali.length;i++){
				ali[i].onclick=function(){
					// window.getComputedStyle非IE
					//currentStyle   IE
					// return window.getComputedStyle?window.getComputedStyle(obj,null).backgroundColor :obj.currentStyle.backgroundColor;
					var color=window.getComputedStyle?window.getComputedStyle(this,null).backgroundColor:this.currentStyle.backgroundColor;
					document.getElementsByTagName('body')[0].style.background=color;
				}
			}
		</script>
	</body>
</html>

對樣式進行封裝一下:

var ali=document.getElementById('myul1').getElementsByTagName('li');
			for(var i=0;i<ali.length;i++){
				ali[i].onclick=function(){
					var color=getStyle(this,'backgroundColor');
					document.getElementsByTagName('body')[0].style.background=color;
				}
			}
			function getStyle(obj,attr){
				//非IE瀏覽器
				if(window.getComputedStyle){
					return window.getComputedStyle(obj,null)[attr];
				}else if(obj.currentStyle){//IE瀏覽器
					return obj.currentStyle[attr];
				}
				return null;
			}

基於IE瀏覽器的非行內獲取法:使用 obj.currentStyle["attr"];基於非IE瀏覽器,如火狐谷歌等非行內獲取法:使用window.getComputedStyle(obj)["attr"]

切記:非行內樣式獲取法,只能獲取不能設置,一般情況下,通過js設置的樣式都是內聯樣式。

.與[]的區別

(1).與[]均可以用於獲取對象屬性,但是寫法存差異。.後面直接跟屬性,[]中的屬性需要以字符串或變量的形式傳入。

設置obj的背景爲#f00。

.的書寫方式:

obj.style.backgroundColor='#f00';

[]的書寫方式:

obj.style['backgroundColor']='#f00';

(2).不能傳入變量,而[]可以傳入變量
 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章