JS对元素样式的操作

时间:4年前   阅读:5873

如果想用javascript获取一个元素的样式信息,首先想到的应该是元素的style属性。但是元素的style属性仅仅代表了元素的内联样式,如果一个元素的部分样式信息写在内联样式中,一部分写在外部的css文件中,通过style属性是不能获取到元素的完整样式信息的。

<!DOCTYPE html>    
<html>    
	<head>    
		<meta charset="UTF-8">    
		<title></title>    
		<style type="text/css">    
			#hd{    
				width: 500px;    
				height: 300px;    
				background: olive;    
				margin: 50px auto;    
			}    
		</style>    
		<script type="text/javascript">    
			window.onload = function(){    
				var hd = document.getElementById('hd');    
//				alert(hd.style.width);   这亲是获取不了的,因为下面body id里面没有设置    
//				这个写法有两种浏览器,先判断浏览器(这种写法可以不管是行内样式,还是嵌入样式,引入导入样式通通可以能获得最终的样式(这里例如写一个宽度))    
				if (document.all) {//IE    
					var w = hd.currentStyle.width;    
//					background比较特殊,这样写是获得不了背景颜色的    
//					var w = hd.currentStyle.background;    
//					要这样写,才能获得背景颜色 下面的W3C标准的那个会以rgb()形式体现出来的    
//					var w = hd.currentStyle.backgroundColor;    
				} else{//W3C标准浏览器    
//					(hd,mull)括号里有两个参数,第一个是你要获得谁的样式'hd',第二个是'null'我也不知道是什么意思,反正要写    
					var w = getComputedStyle(hd,null).width;    
//					background比较特殊,这样写是获得不了背景颜色的    
//					var w = getComputedStyle(hd,null).background;    
//					同上    
//					var w = getComputedStyle(hd,null).backgroundColor;    
				}    
				alert(w);    
			}    
		</script>    
	</head>    
	<body>    
		<div id="hd"></div>    
	</body>    
</html>

本站声明:网站内容来源于网络,如有侵权,请联系我们https://www.qiquanji.com,我们将及时处理。

微信扫码关注

更新实时通知

上一篇:期权合约的分类――新手必看

下一篇:股票和期权两者之间仓位管理有什么不同?

网友评论

请先 登录 再评论,若不是会员请先 注册