【问题标题】:assigning a div a background via javascript is working in jsfiddle.net but not in code通过 javascript 为 div 分配背景在 jsfiddle.net 中有效,但在代码中无效
【发布时间】:2014-10-25 02:30:57
【问题描述】:

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

我已经尝试在现实生活版本中消除所有可能的内容,但这无济于事

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

【问题讨论】:

  • 你有什么问题?
  • 在您的小提琴中,您有很多具有相同 id="abc" 的 DIV。 ID 应该是唯一的。
  • 将背景图像分配给 div id 图像在 jsfiddle 中有效,但在现实生活中不起作用(复制链接)- 谁能帮助我
    多个 abc id 只是填充暂时文字
  • 除非您发布您的“现实生活”代码,否则我们无法为您提供帮助。
  • 它在复制的 zip 文件夹中?

标签: javascript html css


【解决方案1】:

您需要在加载 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/

【讨论】:

  • 感谢您的尝试,但不幸的是,这似乎不起作用?
  • 如果你没有跳过0,你可以直接做var images = ["01", "02", ...]; 为什么你的数组从1开始?
  • 因为我已经通过逆向工程学习了我的网站编码,因为我看到了其他人是如何做到的,所以有时我会搞砸 - 我真的打算让它随机分配 div 一个从 image01 到 image10 的类,所以我可以让一个 js 控制所有页面,只需一个单独的本地 css 控件块,其中图像用于脚本 - 如果你能告诉我一个更好的方法,我将不胜感激!
  • 我添加了一个更简单的版本。
  • 感谢再次打扰您,但如果您查看此jsfiddle.net/LgjzvcpL/11,这就是我真正想要的脚本 - javascript 可以随机添加类 - 通过图像[RandomNumber] 到#image跨度>
猜你喜欢
  • 2013-01-16
  • 2020-11-10
  • 2012-07-07
  • 1970-01-01
  • 2017-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-18
相关资源
最近更新 更多