I am trying to get jQuery to generate a random background on my site body based off a number. So I'm trying to get it to generate either main1.jpg or main2.jpg and throw it into the body as a background.
For some reason it is only generating main2.jpg. Here is my code:
$(document).ready(function(){
$("body").css({'background' : 'url(images/main1.jpg)'}).hide();
$("body").css({'background' : 'url(images/main2.jpg)'}).hide();
var randomNum = Math.floor(Math.random()*2); /* Pick random number */
$("body").css({'background' : 'url(images/main:eq(' 开发者_Go百科+ randomNum + ').jpg)'}).show(); /* Select div with random number */
});
Thanks, Wade
It is very confusing to see what you are trying to do. Right now you are hiding the body twice, then incorrectly adding a css rule, then showing the body. If you just want to set a random background, do this:
$(document).ready(function(){
var randomNum = Math.ceil(Math.random()*2); /* Pick random number between 1 and 2 */
$("body").css({'background' : 'url(images/main' + randomNum + '.jpg)'});
});
If you are wanting to add two divs
and show one randomly, do this:
$(document).ready(function(){
/* Pick random number between 1 and 2 */
var randomNum = Math.ceil(Math.random()*2);
$.each([1,2], function(){
var $div = $('<div class="background" style="background-image: url(images/main' + this + '.jpg)"></div>');
if( this !== randomNum ) $div.hide();
$div.appendTo( document.body );
});
})
The reason it's doing that is the first call to setting the body background overwrites the first. It's the equivalent of doing:
var s = "hello";
s = "world";
alert(s); // world
What you want is something more like:
// this can contain as many images as you want
var images = ["images/main1.jpg", "images/main2.jpg"];
// preload. This is optional
var preload = new Array(images.length);
for (var i=0; i<images.length; i++) {
preload[i] = $("<img>").("src", images[i]);
}
// assign one randomly
$(function() {
var img = images[Math.floor(Math.random() * images.length)];
$("body").css("background", "url(" + img + ")");
});
You could also adjust this to only preload the one image you use for the body background.
var img = images[Math.floor(Math.random() * images.length)];
var preload = $("<img>").attr("src", img);
$(function() {
$("body").css("background", "url(" + img + ")");
});
精彩评论