js获取元素的宽高的方法

HTML代码:
<section class="sec"  style="width: 400px;">
<style type="text/css">
	.sec {
		background-color: red;
		overflow: hidden;
		/*width: 500px;*/
	}
	.child {
		background-color: yellow;
		height: 100px;
		margin-top: 20px;
	}
</style>
	<article class="child"></article>	
</section>

js代码:

var dom = document.getElementsByClassName('sec')[0];
	var w1 = dom.style.width;	//此api只能获取到内联样式的属性值
	var w2 = dom.currentStyle.width;  //此api虽然支持全部三种设置样式的方式,但是只支持IE
	var w3 = window.getComputedStyle(dom).width;	//此api支持IE、Chrome、Firefox的全部三种样式
	var w4 = dom.getBoundingClientRect().width; //同样能获取及时的尺寸,支持IE、Chrome、Firefox,只是获取到的是数值不带单位
	dom.onclick = function () {
		 alert(w4)
	}


猜你喜欢

转载自blog.csdn.net/qq_25695065/article/details/79936399
今日推荐