问题描述:

I am a js newbie. I Have looked for answers to this particular issue but have not found an answer yet in this forum or others, so sorry if it's here and I missed it. I have a script that works for loading a random image from an array to an id element placed directly in the html when the page loads.

I'm trying to see if I can get it to do the same thing but do it for a background image in a id element in a css file. I have firebug and it doesn't give me any error messages with this but it doesn't work either.

window. onload = choosePic;

var myPix = new

Array("images/image1.gif", "images/image2.gif");

function choosePic() {

randomNum = Math.floor((Math.random() * myPix.length));

document.getElementById("headerAnimation").style.backgroundImage.src = myPix[randomNum];

}

网友答案:

You have it almost right.

window.onload = choosePic;

var myPix = new Array("images/image1.gif", "images/image2.gif");

function choosePic() {
    var randomNum = Math.floor((Math.random() * myPix.length));
    document.getElementById("headerAnimation").style.backgroundImage =
        "url(" + myPix[randomNum] + ")";
}
相关阅读:
Top