Execute function based on screen size

前端 未结 4 1855
情书的邮戳
情书的邮戳 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:13

    If you're talking about the monitor's resolution settings, consider window.screen, for instance I am using 1280 x 1024 so mine reports

    window.screen.height; // 1024
    window.screen.width;  // 1280
    

    You could also use the avail prefix to ignore things like the task bar. If you just want to work out the browser's visible area then you would use clientHeight and clientWidth on the documentElement, i.e.

    document.documentElement.clientWidth;  // 1263 (the scrollbar eats up some)
    document.documentElement.clientHeight; //  581 (lots lost here, e.g. to console)
    

    As for your fires-too-often problem, introduce a rate limiter, e.g.

    function rateLimit(fn, rate, notQueueable) {
        var caninvoke = true, queable = !notQueueable,
            ready, limiter,
            queue = false, args, ctx;
        notQueueable = null;
        ready = function () { // invokes queued function or permits new invocation
            var a, c;
            if (queable && queue) {
                a = args; c = ctx;
                args = ctx = null; queue = false; // allow function to queue itself
                fn.apply(c, a);
                setTimeout(ready, rate); // wait again
            } else
                caninvoke = true;
        }
        limiter = function () { // invokes function or queues function
            if (caninvoke) {
                caninvoke = false;
                fn.apply(this, arguments);
                setTimeout(ready, rate); // wait for ready again
            } else
                args = arguments, ctx = this, queue = true;
        };
        return limiter;
    }
    
    var myRateLimitedFunction = rateLimit(
        function () {console.log('foo');},
        2e3 // 2 seconds
    );
    myRateLimitedFunction(); // logged
    myRateLimitedFunction(); // logged after rate limit reached
    

提交回复
热议问题