【发布时间】:2021-01-20 20:21:15
【问题描述】:
我正在抓取下面的元素,例如:
let box = document.querySelector('.zero');
当我在javascript中检查背景颜色时,它显示为"":
box.style.backgroundColor // ""
如果我抓取元素节点,为什么它不将 backgroundColor 列为#DCDCDC,就像我在 CSS 中设置的那样?我认为这是由于元素上有多个类,但不确定原因。
代码:
<div class="tic-tac-box zero">
</div>
.tic-tac-box {
background-color: #DCDCDC;
border-radius: 5px;
border: 2px solid white;
}
【问题讨论】:
-
很可能需要改用
getcomputedstyle。由于 javascript 正在寻找内联样式而不是应用的 css。 -
就像@imvain2 说你会想要
getcomputedstyle,element.style,是你在<Element style="?"/>中放入的内容,或者你可能使用setAttribute('style设置的内容,'')` 等。 -
window.getComputedStyle(box).backgroundColor 会做到的
-
getComputedStyle 为十六进制值提供 rgb 颜色,可能不是预期的结果?
-
我删除了我的答案,这里有一个更好的答案来说明如何获取 CSS 值而不是计算值:stackoverflow.com/questions/46828223/…
标签: javascript css