【问题标题】:Get CSS properties in JS by css class name [duplicate]通过css类名获取JS中的CSS属性[重复]
【发布时间】:2020-08-20 16:05:52
【问题描述】:

如何用js获取元素的CSS属性?假设我有以下内容

.btn {
  background-color: green;
}

.navbtn {
  font-size: 20px;
}

<button id='mybtn' class='btn navbtn' onclick='alert("hi")'>Click me</button>

然后,我想提取元素mybtn 的CSS 属性。如果我这样做了

window.getComputedStyle(document.getElementById('mybtn'))

它返回一个 CSSStyleDeclaration ,其中包含所有 CSS 属性,即使是我没有设置的那些。但是,我想要的是一个包含

的对象(或其他)
{
  background-color: green;
  font-size: 20px;
}

其他所有内容都将视为“默认”。

所以我的问题是:

  1. 是否有这样的功能或库可以完成这项工作?
  2. 如果没有,是否可以在给定类名的情况下获取 CSS 属性(如 getProperties('btn') 返回 { background-color: green; }

提前致谢

【问题讨论】:

  • 这是您问题的答案:stackoverflow.com/a/16966533/1789796
  • @empiric 不是真的。我不知道修改了哪些属性。所以我不能做window.getComputedStyle(document.getElementById('mybtn')).fontSize,因为我不知道fontSize被修改了。

标签: javascript css


【解决方案1】:

就这么简单:

let background = document.querySelector('.btn').style.backgroundColor;
console.log(backround);

【讨论】:

  • 读取特定属性的内联样式。问题是寻找所有的属性集,但不是通过内联样式
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-31
  • 1970-01-01
  • 2012-08-13
  • 1970-01-01
  • 1970-01-01
  • 2012-06-01
  • 2012-05-04
相关资源
最近更新 更多