开发者

How to detect window size and then do something with jquery switch statement

开发者 https://www.devze.com 2023-04-02 06:17 出处:网络
i would like to check for the window size with jquery and based on the different resolutions i would like to change the background image. So i was thinking to somehow use the \"switch\" statement for

i would like to check for the window size with jquery and based on the different resolutions i would like to change the background image. So i was thinking to somehow use the "switch" statement for more cases, but i just don't know how this would look like. This is the basic structure i want but with more options:

开发者_运维问答
if ((screen.width>=1024) && (screen.height>=768)) {
 //do something
}
else {
//do something else
}

Thanks for your help.


You should use:

$(window).width();   // returns width of browser viewport
$(document).width(); // returns width of HTML document

$(window).height();   // returns heightof browser viewport
$(document).height(); // returns height of HTML document

and then you could do:

var width = $(window).width(); 
var height = $(window).height(); 

if ((width >= 1024  ) && (height>=768)) {
 //do something
}
else {
//do something else
}

EDIT - i don't think that using a switch statement is useful in this case. The switch statement is just an alternate way for the if...else notation that in this case i find more useful because you have multiple comparison to do:

if ((width >= 1280) && (height>=1024)) {
 //do something
}
else if ((width >= 1024  ) && (height>=768)){
//do something else
} else if ((width >= 800) && (height>=600)){
//do something else
}else{
//do something else
}


The switch statement won't let you do stuff like checking for numbers between certain values, and it won't let you check on multiple variables, either...

So for this particular scenario, I think the best fit is actually just a list of if-elseif statements, like you're already on your way to do.

To do "range checks" in switch is really verbose:

switch(windowWidth) {
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
        //Do something if value is less than or equal to 5
        break;
    case 6:
    case 7:
    case 8:
    case 9:
    case 10:
        //Do something if value is higher than 5 AND less than or equal to 10
        break;
    ...
    ...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消