简体   繁体   中英

Background should adapt to content height using JQuery on window resizing

The content of a div will be set dynamically. The div #background, should adapt to the height that (separate) div will have. The background also should adapt to resizing of the div when the browser is resized. So the action should happen when the page loads , or when the browser is resized .

<div id="wrapper">
<div id="background"></div>
<div id="content">
    <p>This content will be set dynamically.
        <br>The div #background should adapt to this height.
        <br><br><br><br><br><br>
        <br>This should happen when the page loads,
        <br>or when the browser is resized.
        <br>At this moment, it only works when
        <br>the page loads.
        <br>
    </p>
    <!-- end #content -->
</div>
<!-- end #wrapper -->

At this moment, it only works when the page loads eventhough I added this code:

$(window).resize(function () {
    $("#background").css({
        height: ($("#wrapper").height() + 50) + 'px'
    });
});

How can I get the resizing bit working? Thanks.

here is a jsfiddle to test this

Your resize handler is working as intended, but the issue is that #wrapper won't change height unless you give it height, so right now you're simply updating the height on #background to the same value each time resize is fired:

$(window).resize(function () {
    $("#background").css({
        height: ($("#wrapper").height() + 50) + 'px'
        //       ^^^^^^^^^^^^^^^^^^^^^^ this value never changes
    });
});

Here's an updated demo where I've added

html, body, #wrapper { height: 100%; }

Demo

use display: inline-block .

$(window).resize(function () {
    $("#background").css('display': 'inline-block');
});

You should use .on() :

$(window).on("resize load", function () {
    $("#background").css({
        height: ($("#wrapper").height() + 50) + 'px'
    });
});

does that work for you?

Trigger it on load.

$(window).resize(function () {
    $("#background").css({
        height: $("#wrapper").height() + 50
    });
}).trigger("resize");

http://api.jquery.com/trigger/

http://jsfiddle.net/dzdH5/

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