简体   繁体   中英

Using jQuery to set height of an element dynamically; how to reset height on .resize() event?

Consider this example:

jQuery(document).ready(function($){

    function elementHeight() {

        // Get height of the browser viewport
        var windowH = $(window).height();

        // Set element's height (i.e. #elementID) equal to
        // that of the browser's viewport
        $('#elementID').height(windowH+'px');
    }

    elementHeight();

    // Make sure the height is recalculated and set on the
    // element when the browser is resized
    $(window).resize(function() {
        elementHeight();
    });

});

The code above sets the height of element #elementID so that it's equal to the height of the browser's viewport.

But the browser's viewport size changes when it's resized and ideally, so should the element's height. So, I want the code to also change the height of #elementID so that it's always equal to the browser's viewport, ie even when the browser is resized by the user.

I tried using the .resize() event, as you can see in the code above, but I seem to be doing it wrong.

Because instead of replacing the height of the element (initially calculated when the code is run for the first time), the height keeps adding up (x + y + z + ...) everytime the browser is resized, making the element's height bigger and bigger.

What am I doing wrong? And how should it be done?


NOTE: I also tried these instead of $('#elementID').height(windowH+'px');

$('#elementID').css('height',windowH+'px');

$('#elementID').attr('style', 'height:'+windowH+'px;');

They didn't make any difference.

Try this:

$('#elementID').height(windowH);

If you want to add the px I think this is how it should be done:

$('#elementID').css('height',windowH + 'px');

I would be anyways recommend using the .css as it is faster :)

In jQuery you could do something like

function checkResizeAndReady() {
   var windowHeight = $(window).height();
   $('#height').css('height', windowHeight + "px");
}

$(window).on("resize", checkResizeAndReady);
$(document).on("ready", checkResizeAndReady);

http://codepen.io/RobErskine/pen/efEGc/

Or conversely, you could use CSS:

body,html{
   display:block;
   width:100%;
   height:100%;
   margin:0;
}

#filler{
    height:100%;
    background-color:red;
 }

http://codepen.io/RobErskine/pen/aezkG/

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