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

限于喜欢 提交于 2019-12-03 07:08:36

问题


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.


回答1:


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;
    ...
    ...
}



回答2:


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
}


来源:https://stackoverflow.com/questions/7306933/how-to-detect-window-size-and-then-do-something-with-jquery-switch-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!