简体   繁体   中英

Why aren't my elements correctly sized when the page loads?

I'm trying to get a navigation to hide if there isn't enough room in the window. The navigation is contained in a wrapper that also contains a logo, and so to calculate if there is enough room I use the following:

if ($(window).width() < ($('#logo').outerWidth() + $('#nav').outerWidth())) 
    $('#nav').hide();

I have that run when the document is ready and when the window is resized. What I noticed was if the window started off too small it wasn't hiding the nav so I looked into it further. What I found is the nav width that is being calculated when the document is ready is incorrect.

The nav consists of

  • and they are all calculated to be about 3-4px too small, but when resizing the window the values get correctly calculated. Does anyone know why this might be?

  • It could be that some images haven't fully loaded when the function is called. Try binding the event to;

    $(window).load();
    

    instead of;

    $(document).ready();
    

    This will make the function run after the page has completely finished loading, including images whereas $(document).ready() only waits for the DOM to load.

    $(window).load(function () {
        if ($(window).width() < ($('#logo').outerWidth() + $('#nav').outerWidth()))
            $('#nav').hide();
    });
    

    As Terry pointed out , on a very resource heavy site this would result in a large delay before hiding the nav bar which could be a problem, so you could instead check the status of the #nav or #logo element's load.

    $('#nav').load(function () {
        if ($(window).width() < ($('#logo').outerWidth() + $('#nav').outerWidth()))
            $('#nav').hide();
    });
    

    The problem typically comes from the fact that the browser is still computing the size of the elements when you call your line of code. Try to keep an eye on what sizes you are changing in your $(document).ready() function (would have been good to paste the whole code here...). Any change to the size of an element could affect all others.

    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