简体   繁体   中英

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.

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. On the second run, it already has a height set so it's always the same value. 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.

You can use this

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

Like Chris Empx mentioned, this is easily obtainable with CSS.

Also, you could optimize the code like this fiddle

i wonder why you want to do that with jquery. i would do that in 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

    .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%

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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