gpt4 book ai didi

javascript - 如何检查元素应用了哪些样式?

转载 作者:行者123 更新时间:2023-11-28 02:58:41 28 4
gpt4 key购买 nike

我有一个 HTML 对象元素,可通过以下方式检索

document.getElementById()

有什么方法可以找出该元素应用了哪些样式?不仅仅是 CSS 属性中设置的类名。我需要的是类似于FireBug(FF Addons)的样式检查功能。这可以用 JavaScript 完成吗?

最佳答案

您应该可以通过 getComputedStyle() 执行此操作。然后您可以使用 getPropertyValue()提取您正在寻找的任何 CSS 规则,或者您只需迭代所有值:

let element = document.getElementById("test");
let styles = window.getComputedStyle(element);

let bg = styles.getPropertyValue("background-color");
let fg = styles.getPropertyValue("color");

console.log(bg);
console.log(fg);
div {
color: #333;
border-radius: 0.25rem;
}
<div id="test" style="background: #ccc">Hello World</div>

但是请注意,MDN 中的这两个重要引用:

The returned style is a live CSSStyleDeclaration object, which updates automatically when the element's styles are changed.

还有:

The returned CSSStyleDeclaration object contains active values for CSS property longhand names. For example, border-bottom-width instead of the border-width and border shorthand property names.

关于javascript - 如何检查元素应用了哪些样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1833651/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com