简体   繁体   English

调整高度时不会重新计算Div高度

[英]Div height doesn't get recalculated on resize

It works perfectly when I refresh the page, but when I resize it doesn't recalculate the div height. 当我刷新页面时,它可以完美工作,但是当我调整页面大小时,它不会重新计算div的高度。

JSFIDDLE JSFIDDLE

$(document).ready(function() {
    var selectorsArray = ['home', 'about', 'portfolio', 'contact'];
    responsiveResize(selectorsArray);  
$(window).resize(function(){
    var selectorsArray = ['home', 'about', 'portfolio', 'contact'];
    responsiveResize(selectorsArray);  
});
});


function responsiveResize(selectorsArray){
    $.each(selectorsArray, function( index, value ) {
        var cntcnter = $('#'+value+' .content-container');
        var height = $('#'+value+' .content-container').height();
        console.log(height);
        cntcnter.css({'height': height+'px', 'margin-top': '-'+(height/2) +'px'});
    });
}

The reason it's not working is because on the first run, you set a height to the container. 它不起作用的原因是因为在第一次运行时,您为容器设置了height On the second run, it already has a height set so it's always the same value. 在第二次运行中,已经设置了height因此它始终是相同的值。 If the text overflows the container, it's not affecting the new height in this case. 如果文本溢出容器,则在这种情况下不会影响新高度。

If you want to keep using your code, you need to clear/remove the height you added on the previous run. 如果要继续使用代码,则需要清除/删除上一次运行中添加的height

You can use this 你可以用这个

var height = $('#'+value+' .content-container').css('height', '').height();

Like Chris Empx mentioned, this is easily obtainable with CSS. 就像Chris Empx提到的那样,使用CSS可以轻松实现。

Also, you could optimize the code like this fiddle 另外,您可以优化像这样的小提琴

i wonder why you want to do that with jquery. 我想知道为什么要用jquery做到这一点。 i would do that in css. 我会在CSS中做到这一点。

like that 像那样

<div class='container'>
   <div class='column col 12'>
       <p>Your Inputs here</p>
   </div>
<div class='clear'></div>
</div>

then this in css 然后在CSS

    .container {
         margin: 0 auto;
         width: 960px;
    }
    .col-12{
         width: 100%;
    }
.clear {clear: both;}
.column {padding: 0 .8em; float:left;}

col-6 would be width:50% col-3 would be width:25% col-6将为width:50%col-3将为width:25%

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM