Execute function based on screen size

前端 未结 4 1866
情书的邮戳
情书的邮戳 2020-12-29 13:09

I need to execute a specific function based on screen size and screen size changes (Responsive)

So lets say I have 3 functions (For Example)

4条回答
  •  余生分开走
    2020-12-29 13:12

    Meh; here's a solution.

    You could cache the lastBoundry determined to invoke the functions only when a change occurs.

    // define the boundries
    var bounds = [
        {min:0,max:500,func:red},
        {min:501,max:850,func:orange},
        {min:851,func:green}
    ];
    
    // define a resize function. use a closure for the lastBoundry determined.
    var resizeFn = function(){
        var lastBoundry; // cache the last boundry used
        return function(){
            var width = window.innerWidth; // get the window's inner width
            var boundry, min, max;
            for(var i=0; i min && width < max 
                   && lastBoundry !== boundry){
                    lastBoundry = boundry;
                    return boundry.func.call(boundry);            
                }
            }
        }
    };
    $(window).resize(resizeFn()); // bind the resize event handler
    $(document).ready(function(){
        $(window).trigger('resize'); // on load, init the lastBoundry
    });
    

    Fiddle: http://jsfiddle.net/BaNRq/3/

提交回复
热议问题