如何检测窗口大小,然后使用jquery switch语句执行某些操作

Mr.*_*Sam 16 css jquery if-statement switch-statement window-resize

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

if ((screen.width>=1024) && (screen.height>=768)) {
 //do something
}
else {
//do something else
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助.

Nic*_*tti 47

你应该使用:

$(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
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

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

if ((width >= 1024  ) && (height>=768)) {
 //do something
}
else {
//do something else
}
Run Code Online (Sandbox Code Playgroud)

编辑 - 我不认为在这种情况下使用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
}
Run Code Online (Sandbox Code Playgroud)


pei*_*rix 1

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

因此,对于这个特定的场景,我认为最合适的实际上只是一个if-elseif声明列表,就像您已经在做的事情一样。

进行“范围检查”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;
    ...
    ...
}
Run Code Online (Sandbox Code Playgroud)