元素未显示设置width/height时IE中无法使用currentStyle获取(默认为auto)

我们知道获取元素的实际宽高在IE中可以使用currentStyle属性。但如果没有显示的去设置元素的宽高,那么使用该属性将获取不到,获取的值为auto。如下

<div>abcd</div>
<script>
	var div = document.getElementsByTagName('div')[0];
	alert(div.currentStyle.width);
	alert(div.currentStyle.height);
</script>

  

IE6/7/8/9中输出的都是auto。如果显示的设置了宽高,那么输出的就是实际宽高。如下

1,通过内联style属性设置

<div style="100px;height:50px;">abcd</div>
<script>
	var div = document.getElementsByTagName('div')[0];
	alert(div.currentStyle.width);
	alert(div.currentStyle.height);
</script>

  

2,通过页面嵌入style标签设置

<style>
	div {
		 100px;
		height: 50px;
	}
</style>
<div>abcd</div>
<script>
	var div = document.getElementsByTagName('div')[0];
	alert(div.currentStyle.width);
	alert(div.currentStyle.height);
</script>

  

都将输出:100px,50px

原文地址:https://www.cnblogs.com/snandy/p/2167056.html