18

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

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

谢谢你的帮助。

4

2 回答 2

56

你应该使用:

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

然后你可以这样做:

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

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

编辑 - 我认为在这种情况下使用 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
}
于 2011-09-05T10:49:00.937 回答
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;
    ...
    ...
}
于 2011-09-05T10:57:59.263 回答