繁体   English   中英

根据屏幕尺寸执行功能

[英]Execute function based on screen size

我需要根据屏幕尺寸和屏幕尺寸变化执行特定功能(响应)

那么就说我有3个功能(例如)

function red() {
    $('div').css('background','#B60C0C')
    .text('Screen Size RED');
    console.log('RED');
}

function orange() {
    $('div').css('background','#EBAE10')
    .text('Screen Size ORANGE');
    console.log('ORANGE');
}

function green() {
    $('div').css('background','#83ba2b')
    .text('Screen Size GREEN');
    console.log('GREEN');
}

当屏幕宽度尺寸为500px或更低时,我需要执行功能green()

并且功能橙色()当屏幕宽度大小为501px至850px时

并且当屏幕宽度大小为851px或更高时功能为红色()

在此输入图像描述

我尝试使用resize(),但问题是在为每个像素重复执行相同功能时调整浏览器大小时执行该功能,这是一种非常糟糕的执行方式

我需要在突破屏幕宽度大小时执行该功能

准备在jsfiddle上使用代码http://jsfiddle.net/BaNRq/

咩; 这是一个解决方案。

您可以缓存lastBoundry,确定仅在发生更改时调用函数。

// 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<bounds.length; i++){
            boundry = bounds[i];
            min = boundry.min || Number.MIN_VALUE;
            max = boundry.max || Number.MAX_VALUE;
            if(width > 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
});

小提琴: http//jsfiddle.net/BaNRq/3/

如果您正在谈论显示器的分辨率设置,请考虑使用window.screen ,例如我使用的是1280 x 1024因此我的报告

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

您还可以使用avail前缀来忽略任务栏之类的内容。 如果您只想计算浏览器的可见区域,那么您将在documentElement上使用clientHeightclientWidth ,即

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

至于你的火灾常常是问题,请引入一个速率限制器,例如

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

使用javascript,您可以获得屏幕大小的值。 从中你可以调用自定义函数来获得你想要的东西。

 //function for screen resize
 function screen_resize() {
        var h = parseInt(window.innerHeight);
        var w = parseInt(window.innerWidth);

        if(w <= 500) {
            //max-width 500px
            // actions here...
            red();
        } else if(w > 500 && w <=850) {
            //max-width 850px
            // actions here...
            orange();
        } else {
            // 850px and beyond
            // actions here...
            green();
        }

    }

我使用window.innerHeight / innerWidth来获取屏幕的高度/宽度而不用/忽略滚动条。

    // if window resize call responsive function
    $(window).resize(function(e) {
        screen_resize();
    });

并且在调整大小时只调用该函数并自动调用page.ready state上的函数。

    // auto fire the responsive function so that when the user
    // visits your website in a mall resolution it will adjust
    // to specific/suitable function you want
    $(document).ready(function(e) {
        screen_resize();
    });

尝试检查输出: OUTPUT :)

希望这可以帮助..

我其实想把它作为对@Nirvana Tikku答案的评论,但我不能因为我没有50个声誉,所以我会在这里发表评论+我将添加一个我自己的解决方案,所以答案空间不会'浪费了。

评论:

我很抱歉(也许)“破坏党”,但要么我没有得到OP的问题,要么我可能误解了解决方案。 这就是我认为OP想要的:一种基于屏幕大小动态执行函数而不执行每个像素重复的函数的方法 在给定的解决方案中,尽管一开始也很难看到,但该函数确实对每个像素执行 尝试将console.log('aaaa')放在返回函数行之间,如下所示:

    return function(){
 console.log('aaaa')
        var width = window.innerWidth; // get the window's inner width

运行该功能,然后点击F12按钮(在Firefox中)并调整窗口大小,你会看到它会调整整个调整大小时间(抱歉无法上传图像 - 没有足够的代表')。

我花了一整天的时间尝试自己复制这个解决方案,这样我就能够根据屏幕大小执行一个功能,但是没有“听”沿途的每个像素。

到目前为止,似乎不可能(除非有人读到这个有解决方案),同时这里是我的代码,恕我直言的方式不那么复杂。

解:

var widths = [0, 500, 850];

function resizeFn() {
if (window.innerWidth>=widths[0] && window.innerWidth<widths[1]) {
red();
} else if (window.innerWidth>=widths[1] && window.innerWidth<widths[2]) {
orange();
} else {
green();
}
}
window.onresize = resizeFn;
resizeFn();

看它工作在https://jsfiddle.net/BaNRq/16/

顺便说一句,答案实际上与@ Vainglory07相同,减去了jQuery

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM