javascript - 如何更改数组中元素的背景颜色
问题描述
我有一个 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 个元素表示。我希望能够有一个按钮,让我可以随机化填充每个元素的颜色
任何帮助,将不胜感激
解决方案
const xx = window.getComputedStyle(searchBtn).getPropertyValue('background-color')
console.log(xx)
您只能通过属性访问内联 css 属性值style
。你需要getComputedStyle
推荐阅读
- sql - 周期函数在 teradata 中未按预期工作
- php - 安装时出现 Wordpress http 500 错误
- r - data.table 在每一列上应用函数
- asp.net-mvc - 接受来自 MVC 控制器的 websocket 升级
- bash - 使用外部实用程序 (plink) 运行 shell 脚本 - 无法提供上下文
- django - 如何在 django urlpatterns 中使用查询字符串重定向?
- node.js - model.find() 在函数中返回空,而在函数外正常工作?
- c# - 如何检查文件哈希是否已使用 C# 更改
- angularjs - 使用角度 5 解析的 css calc() 遇到问题
- linux - 为什么aria2c Linux版比Windows版大很多