通过javascript为div分配背景正在jsfiddle.net中工作但不在代码中

时间:2014-10-25 02:30:57

标签: javascript html css

https://copy.com/XPfxgQeHF78d8lgw是文件的链接 小提琴的链接在这里http://jsfiddle.net/LgjzvcpL/9/

我已尝试在真实版本中删除所有内容,但这无济于事

document.getElementById("image").style.backgroundImage = "url(" + dir + images[randomCount] + ".jpg" +  ")"; 

1 个答案:

答案 0 :(得分:0)

您需要在加载DOM后运行代码。将其移至</body>标记之后,或在window.onload处理程序中运行。

此外,您的作业声明需要以;结束,而不是,

window.onload = function() {
    var dir = 'http://seriousphotography.co.uk/HD-Site/images/album/01/';
    var randomCount = Math.round(Math.random() * (imgCount - 1)) + 1;
    var images = new Array;
    images[1] = "01";
    images[2] = "02";
    images[3] = "03";
    images[4] = "04";
    images[5] = "05";
    images[6] = "06";
    images[7] = "07";
    images[8] = "08";
    images[9] = "09";
    images[10] = "10";
    document.getElementById("image").style.backgroundImage = "url(" + dir + images[randomCount] + ".jpg" +  ")"; 
};

将它写成:

会更简单
window.onload = function() {
    var dir = 'http://seriousphotography.co.uk/HD-Site/images/album/01/';
    var images = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10"];
    var randomCount = Math.floor(Math.random() * images.length);
    document.getElementById("image").style.backgroundImage = "url(" + dir + images[randomCount] + ".jpg" +  ")"; 
};

请参阅Get random item from JavaScript array

使用类和jQuery,它将是:

$("#image").addClass("image"+images[randomCount]);

小提琴:http://jsfiddle.net/barmar/LgjzvcpL/12/