jQuery 如何检测窗口大小然后用jquery switch语句做一些事情

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7306933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:40:19  来源:igfitidea点击:

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

jqueryif-statementswitch-statementwindow-resizecss

提问by Mr. Sam

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:

我想用 jquery 检查窗口大小,并根据不同的分辨率我想更改背景图像。所以我想以某种方式在更多情况下使用“switch”语句,但我只是不知道这会是什么样子。这是我想要的基本结构,但有更多选择:

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

Thanks for your help.

谢谢你的帮助。

采纳答案by peirix

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

switch语句不会让您执行诸如检查某些值之间的数字之类的操作,也不会让您检查多个变量...

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

所以对于这个特定的场景,我认为最合适的实际上只是一个if-elseif陈述列表,就像你已经在做的那样。

To do "range checks" in switchis really verbose:

做“范围检查”switch真的很冗长:

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

回答by Nicola Peluchetti

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:

编辑 - 我认为在这种情况下使用 switch 语句没有用。switch 语句只是 if...else 符号的另一种方式,在这种情况下我觉得更有用,因为你有多重比较要做:

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
}