2

To begin, here is the page.

I've attempted the Javascript code without success, so I will try to explain my current setup.

my body has an ID of #homepage. This is the only page I will need this code for, so I've assigned that ID. The following is the CSS to access the image and cover the page:

body#homepage {
    background-attachment: fixed;
    background-image: url(../images/bg/4.jpg);
    background-repeat: no-repeat;
    background-position: center bottom; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

There are 4 images in the "../images/bg" folder, numbered 1 through 4. I simply want the images to change between the 4 upon page load, but I need to keep the images styled as they are in the current CSS.

Since I am only vaguely familiar with Javascript, I believe I'm getting something very simple wrong in the Javascript. I would appreciate someone spelling this out for me in specific detail. Thanks so much!

4

4 回答 4

2

尝试这个

var randomImage = Math.floor((Math.random()*4)+1);
var homePage = document.getElementById('homepage');

homePage.style.backgroundImage='url("..\/images\/bg\/'+randomImage+'.jpg")';
于 2013-10-28T18:11:03.673 回答
0

首先,您需要获取 1 到 4 的随机数。

我将向您展示纯 JavaScript 和 jQuery 方法:

JavaSript方式:

//get random number from 1 to 4 and assign '.jpg' - or other format you need
var randomImage = "..\/images\/bg\/" + Math.floor((Math.random()*4)+1) + '.jpg';

//get body by ID
var homePageBody = document.getElementById('homepage');

//asign random image to body
homePageBody.style.backgroundImage=randomImage;

jQuery方式:

$(document).ready(function () {
    var randomImage = '../images/bg/' + randomFromTo(1, 4) + '.jpg';

    //set background to body #homepage
    $('#homepage').css("background-image", randomImage)
});

//define randomizer function
function randomFromTo(rfrom, rto) {
    return Math.random() * (rfrom - rto) + rfrom;
}
于 2013-10-28T18:26:17.383 回答
0

document.getElementById('homepage').style.backgroundImage = 'url(/whatever/img' + Math.floor( Math.random()*4 ) + '.png)';

于 2013-10-28T18:15:38.003 回答
0

用jQuery

$(document).ready(function(){
var num = getRandomArbitrary(1,4);
$('#homepage').css("background-image",'../images/bg/' + num + '.jpg')
});

function getRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min;
}
于 2013-10-28T18:12:13.543 回答