div的子级是相同的高度减去顶部和底部的paddding

时间:2016-05-27 12:11:14

标签: javascript jquery html

希望将子div的高度设置为与父div相同。随着页面调整大小,div越来越大。这是一个搜索结果,所以有很多相同的代码块。

function legendHeight() {
    $result = $('.search-result');
    $resultHeight = $result.height(); 
    if($result.find('.legend-lead').length != 0) {
      $(this).children('.legend').height($resultHeight);
    }
};


$(window).load(function () {
    equalheight('.search-result');
    legendHeight();
});
$(window).resize(function () {
    equalheight('.search-result');
    legendHeight();
});

这是一个显示我的意思的JSFiddle:https://jsfiddle.net/o0nzo47k/

虽然盒子应该调整大小(不是为什么不起作用),如果你调整窗口大小,你会看到蓝色的div变得越来越高。

1 个答案:

答案 0 :(得分:1)

好的,这是您的示例正常工作https://jsfiddle.net/3wnLeoyd/

内部divs高度(.legend-lead-key.legend-lead-address)我只使用css处理它们而我在外部高度上使用了jquery(以使每个div的高度相同)

css:

.search-result{
  border-top: none;
  margin-top: 0 !important;
  padding: 20px;
  padding: 1.25rem;
  margin-left: 2.34741784%;
  margin-bottom: 1.875rem;
  background: red;
  width: 25%;
  display:inline-block;
  vertical-align:top;
}

.search-result:nth-child(3n+1) {
  margin-left: 0;
}

.legend-lead{
  display:table;  
}

.legend-lead-key {
  background: blue;
  border-right: 1px solid #c7cada;
  display:table-cell;
}

.legend-lead-address{
  display:table-cell;
}

js:

function equalheight(){
    var maxHeight = 0;
  $('.search-result .legend-lead').height('auto');
    $('.search-result').each(function(){
    if($(this).height()>=maxHeight){
        maxHeight = $(this).height();
    }
  })
  return maxHeight;
}

$(window).load(function(){
    $('.search-result .legend-lead').height(equalheight());
})

$(window).resize(function(){
    $('.search-result .legend-lead').height(equalheight());
})