【问题标题】:Get current applied style with JS使用 JS 获取当前应用的样式
【发布时间】:2015-03-28 00:12:39
【问题描述】:

我在看这个帖子 How to get the background color of an element using javascript?

确认如果你这样做了

div.style.color 

您将获得应用于 div 的颜色。

但是,如果样式被内联应用于元素,这似乎只会返回结果?

当样式通过样式表(或在标签中)而不是直接内联时,如何返回应用于元素的样式?

请参阅下面的示例。

console.log(document.getElementById('content').style.backgroundColor);
console.log(document.getElementById('content').style.color);
#content {
  background-color: #000000;
  display: inline-block;
  height: 100px;
  width: 100px;
}
<div id="content" style="color:red;"></div>

console.log(document.getElementById('content').style.backgroundColor);

什么都不返回

console.log(document.getElementById('content').style.color);

返回红色

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    您需要使用getComputedStyle() 来获取通过样式表分配的样式。

    console.log(getComputedStyle(document.getElementById('content')).backgroundColor);
    console.log(document.getElementById('content').style.color);
    #content {
      background-color: #000000;
      display: inline-block;
      height: 100px;
      width: 100px;
    }
    <div id="content" style="color:red;"></div>

    【讨论】:

      猜你喜欢
      • 2011-04-04
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 2021-04-03
      • 2016-07-07
      • 1970-01-01
      相关资源
      最近更新 更多