简体   繁体   中英

I need to set the height of a div according to the size of the window when the page is loaded and when the page is resized

I need a function that sets the height of a div according to the size of the window when the page is loaded and when the page is resized.

Instead I have a function that only adds to the length of the div, only when the window is resized.

I am not good at javascript myself, and this is the very last thing I need before my webpage is completed, so any help would be greatly appreciated!

This is the page, and the div in question is the light gray infobox (containing text and a button) on the left: http://goodshitdesign.no/

This is the code for the function I currently have:

<script>
$(document).ready(function() {
    $(window).on("resize", function() {

        var bodyheight = $(document).height();

        $(".infobox").height(bodyheight);
    });
});
</script>

No need of using Javascript to set the dimensions relative to the viewport.

Use viewport percentage height

1/100th of the height of the viewport.

.infobox {
    height: 100vh;
}

If you still want to use JS( I don't know why when using CSS will be better approach ),

  1. resize event binding is not required to be wrapped in ready
  2. To get window height use $(window).height()
  3. Use trigger to force execute event handler on page load

Code:

$(window).on("resize", function () {
    $(".infobox").height($(window).height());
    //                   ^^^^^^^^^
}).trigger('resize');
// ^^^^^^^^^^^^^^^^^

Have you considered using vh and vw CSS units instead of JavaScript?

.infobox { width: 100vh; height: 100vh; }
<script>
$(document).ready(function() {
    $(".infobox").height($(window).height());
    $(window).on("resize", function() {
        $(".infobox").height($(window).height());
    });
});
</script>

'resize' do not run when page is loaded. Therefore on page ready you just create a event handler for resizes that will occur in the future.

your script works as it is. in order to resize your div onload, simply call the .resize method without any parameters.

<script>
$(document).ready(function() {
    $(window).on("resize", function() {
        var bodyheight = $(document).height();
        $(".infobox").height(bodyheight);
    });
    $(window).resize(); // THIS EMULATES THE RESIZE EVENT ONDOCUMENTREADY
});
</script>

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