首页 > 解决方案 > 如何更改数组中元素的背景颜色

问题描述

我有一个 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 个元素表示。我希望能够有一个按钮,让我可以随机化填充每个元素的颜色

任何帮助,将不胜感激

标签: javascripthtmlrandom

解决方案


const xx = window.getComputedStyle(searchBtn).getPropertyValue('background-color')
console.log(xx)

您只能通过属性访问内联 css 属性值style。你需要getComputedStyle


推荐阅读