我一直在尝试通过找出用户的屏幕分辨率来改变学校项目的背景,这是我的代码:
var width = window.innerWidth;
var height = window.innerHeight;
function getResolution(){
if (width <= 800 && height <= 600) {
document.body.style.backgroundImage ="url(Images/ResBackgrounds/800x600.jpg)";
}
if (width <= 1024 && height <= 768) {
document.body.style.backgroundImage ="url(Images/ResBackgrounds/1024x768.jpg)";
}
if (width <= 1152 && height <= 864) {
document.body.style.backgroundImage ="url(Images/ResBackgrounds/1152x864.jpg)";
}
if (width <= 1280 && height <= 720) {
document.body.style.backgroundImage ="url(Images/ResBackgrounds/1280x720.jpg)";
}
if (width <= 1280 && height <= 768) {
document.body.style.backgroundImage ="url(Images/ResBackgrounds/1280x768.jpg)";
}
if (width <= 1280 && height <= 800) {
document.body.style.backgroundImage ="url(Images/ResBackgrounds/1280x800.jpg)";
}
if (width <= 1280 && height <= 960) {
document.body.style.backgroundImage ="url(Images/ResBackgrounds/1280x960.jpg)";
}
if (width <= 1280 && height <= 1024) {
document.body.style.backgroundImage ="url(Images/ResBackgrounds/1280x1024.jpg)";
}
if (width <= 1360 && height <= 768) {
document.body.style.backgroundImage ="url(Images/ResBackgrounds/1360x768.jpg)";
}
if (width <= 1366 && height <= 768) {
document.body.style.backgroundImage ="url(Images/ResBackgrounds/1366x768.jpg)";
}
if (width <= 1440 && height <= 900) {
document.body.style.backgroundImage ="url(Images/ResBackgrounds/1440x900.jpg)";
}
if (width <= 1600 && height <= 900) {
document.body.style.backgroundImage ="url(Images/ResBackgrounds/1600x900.jpg)";
}
if (width <= 1680 && height <= 1050) {
document.body.style.backgroundImage ="url(Images/ResBackgrounds/1680x1050.jpg)";
}
if (width <= 1920 && height <= 1080) {
document.body.style.backgroundImage ="url(Images/ResBackgrounds/bkg.jpg)";
}
}
由于某些原因,它总是跳到最后一个if结构,即1920x1080结构,在任何分辨率下。
我想这是我做的基本结构,也许应该是if else{},它确实适用于1920x1080p
你真的应该使用CSS媒体查询。
@media screen and (max-width: 800px) , screen and (max-height: 600px) {
background-image:url("Images/ResBackgrounds/800x600.jpg");
}
等你的if语句都是触发的,所以因为几乎每个屏幕分辨率都在1920x1080以下,所以最后的语句每次都会触发。
只使用if else
,以便一旦找到匹配的条件,它就停止检查if
的其余语句。
您测试的不是屏幕分辨率,而是浏览器窗口的大小。我会使用CSS媒体查询:
css代码: @media screen and (min-width : 966px) {
body { backgound-image: url('pix/someimage1.png')
}
@media screen and (max-width: 966px) and (min-width: 800px){
body { backgound-image: url('pix/someimage2.png')
}
等。(制定更多规则)
这样,当窗口大小调整时,背景也会被更新,你不必监听窗口大小调整事件
你必须为屏幕分辨率使用范围,而不仅仅是小于或等于。
if (width <= 800 && height <= 600) {
document.body.style.backgroundImage ="url(Images/ResBackgrounds/800x600.jpg)";
}
else if (width >= 1024 && width < 1152 && height >= 768 && height < 864) {
document.body.style.backgroundImage ="url(Images/ResBackgrounds/1024x768.jpg)";
} ...
差不多。但这并不有效。