获取DOM元素样式

1、obj.currentStyle.styleName   只兼容IE

2、getComputedStyle(obj, false).styleName  不兼容IE8

于是有了兼容性写法:

function getStyle(obj, sName){
	return (obj.currentStyle || getComputedStyle(obj, false))[sName];
}

  demo:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>DEMO - Lik</title>
	<style>
		div{
			width:100px;
			height:200px;
			background:blue;
		}
	</style>
</head>
<body>
	<div></div>
	<script>
		function getStyle(obj, sName){
			return (obj.currentStyle || getComputedStyle(obj, false))[sName];
		}
		var oDiv = document.getElementsByTagName('div')[0];
		console.log(getStyle(oDiv, 'width'));	    // 100px
		console.log(getStyle(oDiv, 'height'));	    // 200px
		console.log(getStyle(oDiv, 'background'));   // rgb(0, 0, 255) none repeat scroll 0% 0% / auto padding-box border-box
	</script>
</body>
</html>

  

posted @ 2017-07-09 16:55  likwin  阅读(381)  评论(0编辑  收藏  举报