js获取一个div的height(width)并赋值给另一个div

版权声明: https://blog.csdn.net/Yugoup/article/details/84147713

js获取一个div的height并赋值给另一个div


当div的高度是动态的,而父级div的高度不能自适应,这个时候可以用js来动态获取子div的动态height,并赋值给父级div

假设父级div无法随着子div的高度改变而改变

首先是HTML页面,这里我就举个例子

<div id="faster">
	<div id="son">
		这个div高度为动态,并且大于父级div的高度
	</div>
</div>

CSS部分

<style>
	#faster{
		width: 500px; 
		height: 200px; 
		background: red;
	}
	#son{
		width: 200px; 
		height: 400px; 
		background: deepskyblue;
		float: right;
	}
</style>

真是个丑到无法呼吸的页面

好丑啊!!!!!

js部分,这里提供原生写法和jQ写法
可以使用offsetHeight方法

//原生js
<script>
	var fasterheight = document.getElementById('faster');
		var sonheight = document.getElementById('son');
		fasterheight.style.height = sonheight.offsetHeight+'px';
</script>
//jQ写法
<script src="http://code.jquery.com/jquery-1.4.1.js"></script>//使用jquery需要引用官方文件
<script>
		window.onload = function() { 
			var fasterHeight = $('#son').height(); 
   		$("#faster").css({height: fasterHeight+'px'});
  }
</script>

效果如下:
在这里插入图片描述
获取动态宽度方法类似,使用offsetWidth方法

猜你喜欢

转载自blog.csdn.net/Yugoup/article/details/84147713
今日推荐