简体   繁体   中英

Get height of the div on window resize

I have a function that resizes divs depending on how high (in pixels) other divs with the same class are:

<script type="text/javascript">

    function resizeTheDivs(tag){
        // first get the tags to adjust
        var $tags = $('.' + tag);
        var $new_height = 0;
        // find out which one is largest
        $('.' + tag).each(function(){
            $(this).height() > $new_height ? $new_height = $(this).height() : null;
        });
        // make all others that height
        $tags.height($new_height);
        // I console.log($new_height) here sometimes
    }

    // resize divs on document load
    $(document).ready(function(){
        resizeTheDivs('the-class');
    });
    // resize divs on window resize
    $(window).resize(function () {
        resizeTheDivs('the-class');
    });

</script>

The divs resize correctly on page load, but when console.log($new_height) fires from the window resize function, the $new_height is not changed.

Context: There are 3 divs (floated left, so next to each other with 33% width) that contain text in p tags. So when I resize the browser width, the text gets 'longer', but the javascript function isn't picking up the new heights of the divs.

Any ideas?

You need to reset the height to auto before measuring it, or else it will always return the fixed value you set in $(document).ready :

function resizeTheDivs(tag){
    // first get the tags to adjust
    var $tags = $('.' + tag);
    var $new_height = 0;
    // find out which one is largest
    $('.' + tag).each(function(){
        $(this).removeAttr('style');
        $(this).height() > $new_height ? $new_height = $(this).height() : null;
    });
    // make all others that height
    $tags.height($new_height);
    // I console.log($new_height) here sometimes
}

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