首页 > 解决方案 > 如何使用 jQuery 设置 DIV 元素的高度

问题描述

我想实现以下

1)点击 .step2-opt

2) .quiz__drawer div 应该得到 .step2info 的高度

3) HTML 输出应该是

<div class="quiz__drawer" style="height:height of .step2info div">

4) 使用这个 jQuery 代码

$('body').on("click", '.step2-opt', function () {
  $(".quiz__drawer").height(function(){
    $(".step2info").outerHeight();
  });
});

请帮我修复jquery代码。

标签: javascripthtmljquery

解决方案


如您所见,此函数在单击第一个 div 后均衡高度:

$.fn.equalizeHeights = function(){
  return this.height( Math.max.apply(this, $(this).map(function(i,e){ return $(e).height() }).get() ) )
}

function test(){

$('.step2info, .quiz__drawer').equalizeHeights();

}
<script
  src="https://code.jquery.com/jquery-3.5.1.js"
  integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
  crossorigin="anonymous"></script>

<body>
<div class="step2info" onclick="test()">dkdpodkds<br>soskdsopkdspodskpskpkpk<br>sopkspokdspskposkspksapk<br></div>
<div class="quiz__drawer"></div>
</body>


推荐阅读