简体   繁体   English

根据屏幕分辨率更改背景图像

[英]change background image according to the screen resolution

Well i do have the below query which is working fine without any problem. 好吧,我确实有以下查询,它工作正常,没有任何问题。 it is changing the background-image when i open it in explorer. 当我在资源管理器中打开背景图像时,它正在改变。 and when i change the resolution it does not change the background-image automatically i need to refresh the page to change the background image. 当我更改分辨率时,它不会自动更改背景图像,我需要刷新页面以更改背景图像。 i want to change it immediately when i change the screen resolution. 我想在更改屏幕分辨率时立即更改它。

Please help.... 请帮忙....

<script type="text/javascript">
document.onload=pickIt()
function pickIt()
{
    var w=screen.width
    var h=screen.height
    if(w==1440&&h==900)
    {
    //alert("1440x900");
    document.getElementsByTagName('body')[0].style.backgroundImage="url('images/patterns/background-1440x900.png')";
    }
    else if(w==1280&&h==800)
    {
    //alert("1280x800")
    document.getElementsByTagName('body')[0].style.backgroundImage="url('images/patterns/background-1280x800.png')";
    } else if(w==1280&&h==768)
    {
    //alert("1280x768")
    document.getElementsByTagName('body')[0].style.backgroundImage="url('images/patterns/background-1280x800.png')";
    } else if(w==1280&&h==720)
    {
    //alert("1280x720")
    document.getElementsByTagName('body')[0].style.backgroundImage="url('images/patterns/background-1280x800.png')";
    }
}
</script>

为什么不简单地执行document.getElementsByTagName('body')[0].onresize=pickIt吗?

You can use media queries for this. 您可以为此使用媒体查询。 compatibility is still not the best, but it is growing: http://caniuse.com/#feat=css-mediaqueries 兼容性仍然不是最好的,但是它正在增长: http : //caniuse.com/#feat=css-mediaqueries

@media (max-width: 1200px) and (max-height:600px) {
    html {
        background: url(http://lorempixel.com/1200/600);
    }
}
@media (max-width: 900px) and (max-height:500px) {
    html {
        background: url(http://lorempixel.com/900/500);
    }
}
@media (max-width: 700px) and (max-height:500px) {
    html {
        background: url(http://lorempixel.com/700/500);
    }
}
@media (max-width: 500px) and (max-height:300px) {
    html {
        background: url(http://lorempixel.com/500/300);
    }
}

Demo: http://jsfiddle.net/32X57/ 演示: http//jsfiddle.net/32X57/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM