简体   繁体   中英

How to set full page background Image of a div that changes on page load

I tried but couldn't get it done.

I want the background of a div to cover full page according to the device width and it should change each time when page is load or refresh on same system.

I have tried many codes but none of them works for me.

Now the script that i am using is:

<script type="text/javascript">  
window.onload=function(){  
   var thediv=document.getElementById("image");  
   var imgarray = new Array("../bgimages/1.png", "../bgimages/2.png", "../bgimages/3.png");  
   var spot =Math.floor(Math.random()* imgarry.length);  
   thediv.style.background="url("+imgarray[spot]+")";  
}  
</script>

The HTML code is as follows

<html>
<body>
<div id="image">
 <div class = "container"> 
 </div> <!--container ends-->
</div>

I want #image div background to cover full page. This is the CSS i am using:

#image
{
    width:100%;
    height:100%;
    background-repeat:no-repeat;
    background-size:cover;
    background-position:center;
}

Here is the link of the page: http://sahibfreelancer.hostzi.com/ No background image loading. Please if i miss anything you can let me know. I hope i gave enough details. I am trying this from last one day. Will be looking forward to your responses.

I spotted a typo :

var spot =Math.floor(Math.random()* imgarry.length);

... should be ...

var spot =Math.floor(Math.random()* imgarray.length);  

... shouldn't it ? Does it work if you edit that ?

Since you have jQuery in the tags, I'm going to assume you're using jQuery.

But that being said you're not using the $ syntax in your code examples.

Here's how you can set the background with jQuery:

$('#image').css('background-image', 'url(' + imageUrl + ')');

Edit: Looks like Ashugeo got it. Next time check the console for the output of your script, it would have been throwing an exception.

Also, if you are using jQuery, there's nicer ways to do what you're doing.

To make the image occupy the entire screen you can specify the viewport height in css like this #image {height:100vh}

Now for the javascript code everything looks fine to me if the images are in the specified url it should load them randomly. You can see a example here .

the only thing i've done is load the images over the web since i cant access them locally on fiddle. A different Image is loading every time.

As for the page load i've used a immediately invoking function which will fire when the contents are loaded but you can use onload as well.

I think its the path of your images. I pasteD your code and change the url and it works http://jsbin.com/pozadujeca/edit?js,console,output

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