Javascript未返回样式属性

Javascript not returning style properties

本文关键字:属性 样式 返回 Javascript      更新时间:2023-09-26

我有一个简单的脚本,它可以获取元素中文本的颜色并将其打印到控制台。然而,当我运行脚本时,我得到的是一个空字符串,而不是实际的颜色。有人能向我解释为什么以及如何修复它吗?

HTML

<div id="scrollingTextHolder">
    <p id="scrollingText">Hello</p>
</div>

CSS

#scrollingText{
    margin-top: 5%;
    color: black;
}

JS

window.addEventListener("load", function(){
    console.log(document.getElementById("scrollingText").style.color);
})

您可以使用getComputedStyle()getPropertyValue(),颜色也作为rgb(R,G,B) 返回

var a = document.getElementById("scrollingText");
console.log(window.getComputedStyle(a).getPropertyValue('color'))
#scrollingText {
  margin-top: 5%;
  color: black;
}
<div id="scrollingTextHolder">
  <p id="scrollingText">Hello</p>
</div>