简体   繁体   中英

Javascript window resize not firing onload

I'm working off a specific codepen which can be found here https://codepen.io/anon/pen/WXgvjR .. Its not mine.

Everything works perfect with it, except when i open the page on a mobile or change the browser width to be mobile size, its still displaying some items outside the browser window width ways, is there any way to detect a mobile or change in screen size and just display them going down?

The following is the resize code that is found in the codepen if that helps

$(window).resize(function(){
    var margin=40;
    var padding=15;
    var columns=0;
    var cWidth=300;
    var windowWidth = $(window).width();

    var overflow = false;
    while(!overflow){
        columns++;
        var WidthTheory = ((cWidth*columns)+((columns+1)*padding)+margin);
        if(WidthTheory > windowWidth)
            overflow = true;            
    }       
    if(columns > 1)
        columns--;

    var GridWidth = ((cWidth*columns)+((columns+1)*padding)+margin);

    if( GridWidth != $('#grid').width()){
        $('#grid').width(GridWidth);
    }
});

Any help would be greatly appreciated

Resizing using the Maximise, Minimise, or the Chrome DevTools Devices Buttons, etc. does not trigger the resize event properly (it triggers it before actually resizing, so it does not get the right size).

For the mobile page load, put the same code from the window resize function into the document ready function as well (I would recommend making it a function and then call the function in both to reduce duplicate code):

function setDisplayBoardSize()
{
    var margin=40;
    var padding=15;
    var columns=0;
    var cWidth=300;
    var windowWidth = $(window).width();

    var overflow = false;
    while(!overflow){
        columns++;
        var WidthTheory = ((cWidth*columns)+((columns+1)*padding)+margin);
        if(WidthTheory > windowWidth)
            overflow = true;            
    }       
    if(columns > 1)
        columns--;

    var GridWidth = ((cWidth*columns)+((columns+1)*padding)+margin);

    if( GridWidth != $('#grid').width()){
        $('#grid').width(GridWidth);
    }
}


$(window).resize(function()
{   
    setDisplayBoardSize();
});

$(document).ready(function()
{       
    setDisplayBoardSize();
});

For the min-max etc. see this stackoverflow thread:

jQuery resize() using browser maximise button

This answer specifically should help:

$(window).resize(function()
{   
    setTimeout(function() {
        setDisplayBoardSize();
    }, 100);
});

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