Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've tried several tutorial on the web and none seems to work properly. What I'm trying to do is quite simple I think:

I have 9 different .jpg images that I need to randomly show up on page load - to be background. This should be fairly simple right?

Thanks,

EDIT (Sorry, forgot to attach the code - found in the web):

$(document).ready(function(){

    bgImageTotal=9;

    randomNumber = Math.round(Math.random()*(bgImageTotal-1))+1;

    imgPath=('../img/bg/'+randomNumber+'.jpg');

    $('body').css('background-image', ('url("'+imgPath+'")'));

});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
234 views
Welcome To Ask or Share your Answers For Others

1 Answer

Check out this tutorial: http://briancray.com/2009/12/28/simple-image-randomizer-jquery/

First create an array of images:

var images = ['image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg', 'image5.jpg'];

Then, set a random image as the background image:

$('body').css({'background-image': 'url(images/' + images[Math.floor(Math.random() *      images.length)] + ')'});

That should work no problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...