重置通过窗口大小调整功能设置的高度

时间:2019-06-05 23:13:50

标签: jquery html css

我有两列布局,根据其中的内容,每个块的高度都不同。我写了一些使用每一对块的jquery行,并将两个高度中的较大者应用到了两个块上,并且效果很好,但是我需要在Windows调整大小时调整它的大小,而我仍然坚持这样做。 / p>

我尝试将函数包装在window.resize事件中,但这根本不起作用。一旦页面加载并且函数运行一次,高度不再改变,因此,如果我调整窗口大小,内容将溢出。

布局的html代码:

 <div class="catmenu cat61">
    <div class="row">
        <div class="col-md-6">
            <div class="row itemenu par">
              <p>content</p><p>content</p>
            </div>
            <hr class="hrp">
            <div class="row itemenu par">
               <p>content</p><p>content</p>
            </div>
        </div>
        <div class="col-md-6">
            <div class="row itemenu impar">
              <p>longer</p><p>content</p><p>longer</p><p>content</p>
            </div>
            <hr class="hrp">
            <div class="row itemenu impar">
               <p>longer</p><p>content</p><p>longer</p><p>content</p>
            </div>
        </div>
    </div>
</div>
 

在加载时发挥作用的jquery:

 
var height1 = Math.max($( ".cat61 > div > div .row.itemenu.impar:nth-child(1)" ).height(), $( ".cat61 > div > div .row.itemenu.par:nth-child(1)" ).height());
	$(".cat61 > div > div .row.itemenu.impar:nth-child(1), .cat61 > div > div .row.itemenu.par:nth-child(1)").height(height1);
 

我需要在window.resize上运行该函数并根据块在调整大小时呈现的自动高度更新高度,我想我需要以某种方式首先应用自动高度,然后再次运行jquery,但是我不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

使用window.resize事件对您有正确的想法。我怀疑您遇到了以下问题:一旦在页面加载中设置了height值,随后的.height()尝试将返回该第一个派生的height1值。

另一个问题可能是您仅在页面加载时缓存height1,因此在resize上按原样使用它(即不重新计算它)只会将高度设置为值。

如果您创建一种用于调整大小的方法,该方法既清除了所有先前设置的height值,又清除了 值,并重新计算了元素的“自然”高度,则该方法应可以动态地保持行高您期望的方式。

function reset_heights() {

  // CLEAR the last, programmatically set, height values (or they will never change)
  $(".cat61 > div > div .row.itemenu.impar:nth-child(1), .cat61 > div > div .row.itemenu.par:nth-child(1)").height( '' );

  // THEN measure their "natural" heights
  var height1 = Math.max( $( ".cat61 > div > div .row.itemenu.impar:nth-child(1)" ).height(), $( ".cat61 > div > div .row.itemenu.par:nth-child(1)" ).height());

  // THEN set the newly derived max height
  $(".cat61 > div > div .row.itemenu.impar:nth-child(1), .cat61 > div > div .row.itemenu.par:nth-child(1)").height( height1 ); 
}

// set your `resize` listener/handler
$( window ).on( 'resize', function ( event ) {
  reset_heights();
} );

// do your initial page-load resizing
reset_heights();

也就是说,resize会开火很多。这样resize事件处理程序在处理方面可以是“昂贵的”。我建议您稍微使用jQuery Object caching,并考虑使用debouncing