欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

获取DOM元素样式

程序员文章站 2022-06-21 12:06:05
...

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>