简体   繁体   中英

Adding background img if screen resolution width >1028

Hi guys,

I'm fairly new to javascript. I have a pretty simple script I wrote to add a background image if the screen resolution width is bigger than 1028px.

Unfortunately, after trying this (on another computer, with 800x600 resolution), it doesn't work.

I'm not looking to stretch the image, just simply add it if the screen resolution width is bigger than or equal to 1024.

Here is the code:

    <SCRIPT language="JavaScript">
    <!--
    document.write('<style type="text/css">div#container_header_body {background-image:url(\'');
    if (screen.width<1024)
    {
     document.write('none;');
    }
    else
    {
      document.write('images/mmmgirl.png');
    }
    document.write('\');</style>');
    //-->
    </SCRIPT>

<link rel="stylesheet" type="text/css" href="stylesheet.css" />

Can anybody give me some insight into what I'm doing wrong?

Thanks so much. I've already learned a LOT from this place.

- - Andrew

No need for JavaScript, just use a CSS media query :

@media all and (min-width: 1024px) {
    background-image: url(images/mmmgirl.png);
}

Try this jsfiddle :

var screenWidth = screen.width,
    container = document.getElementById('container_header_body');

console.log(screenWidth);

if (screenWidth > 1024) {
     container.style.backgroundImage = 'url(http://oddanimals.com/images/lime-cat.jpg)';
} else {
    container.style.backgroundImage = 'none';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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