根据屏幕尺寸执行功能 [英] Execute function based on screen size

查看:86
本文介绍了根据屏幕尺寸执行功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要根据屏幕尺寸和屏幕尺寸更改执行特定功能(自适应)

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

所以可以说我有3个函数(例如)

So lets say I have 3 functions (For Example)

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()

I need to execute function green() when the screen width size 500px or lower

当屏幕宽度尺寸为501px至850px时,并使用orange()函数

And function orange() when the screen width size 501px to 850px

当屏幕宽度尺寸为851px或更高时,并使用red()函数

And function red() when the screen width size 851px or higher

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

I tried to use resize() but the problem is executing the function when resizing the browser for each pixel repeat executing the same function and this is a very bad way to perform

当我中断屏幕宽度大小的点时,我需要执行该功能

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

Ready to use code on jsfiddle http://jsfiddle.net/BaNRq/

推荐答案

Meh;这是一个解决方案.

Meh; here's a solution.

您可以缓存确定为仅在发生更改时调用功能的lastBoundry .

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<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/

这篇关于根据屏幕尺寸执行功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆