【发布时间】:2021-10-16 18:21:43
【问题描述】:
我有一个包含 5 个 div 的数组
`<div id="cap-left2"</div>`
`<div id="cap-left1"</div>`
`<div id="cap-base"</div>`
`<div id="cap-right1"></div>`
`<div id="cap-right2"</div>`
所有这些 div 都有背景。 在我的 javascript 中,我有:
let items = [capBase,capLeft1,capLeft2,capRight1,capRight2];
这行得通:
`var tom = items[Math.floor(Math.random()*items.length)]
console.log(tom)`
这行得通
`var tom = items[Math.floor(Math.random()*items.length)]`
`console.log(tom.style)`
但我想要 backgroundColor 并且这些都不起作用:
`var tom = items[Math.floor(Math.random()*items.length)]`
`console.log(tom.style.background)`
`var tom = items[Math.floor(Math.random()*items.length)]`
`console.log(tom.style.backgroundColor)`
我想做的是假设我有 5 个样本,由数组中的 5 个元素表示。我希望能够有一个按钮,让我可以随机化填充每个元素的颜色
任何帮助将不胜感激
【问题讨论】:
-
缺少 > ?数组中的名称与 html id 不匹配? tom.style 看起来很不稳定。
-
如果您对此提出质疑,我敢打赌您很快就会得到答案。 :-)
标签: javascript html random