简体   繁体   中英

Stretching image to full screen on html

I have this code which randomly shows a background image. I sized up the images and lower the bytes to lower the loading speed. However, I want the image to resize with whatever the screen size is.

<script type="text/javascript">
    var randnum = Math.random();
    var inum = 3;
    var rand1 = Math.round(randnum * (inum - 1)) + 1;
    images = new Array();
    images[1] = "bgImages/Blue_Venetian_Glass.jpg";
    images[2] = "bgImages/Etched Glass.jpg";
    images[3] = "bgImages/glass.jpg";
    images[4] = "bgImages/Raindrops_on_Glass.jpg";
    var image = images[rand1];
    document.body.style.background = 'url("' + image + '") no-repeat center center fixed';
</script>

My question is "what do I need to make the image stretch"

You can use CSS3 background-size Property. Check this link.

http://www.w3schools.com/cssref/css3_pr_background-size.asp

best way to achieve that effect would be to use a div with the image inside absolute positioned it that you can style.

HTML to add before </body> :

<div align="center"><img src="images/BG.jpg" id="bg"></div>

CSS:

#bg {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: -5000;
}

Javascript:

var randnum = Math.random();
var inum = 3;
var rand1 = Math.round(randnum * (inum - 1)) + 1;
images = new Array();
images[1] = "bgImages/Blue_Venetian_Glass.jpg";
images[2] = "bgImages/Etched Glass.jpg";
images[3] = "bgImages/glass.jpg";
images[4] = "bgImages/Raindrops_on_Glass.jpg";
var image = images[rand1];
document.getElementById('bg').src = image;

您是否尝试过为图像提供一个CSS类,并将该类的height和width属性设置为100%?

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