发布于 2026-01-06 2 阅读
0

如何在 JavaScript 中获取 CSS 值?DEV 的全球展示挑战赛,由 Mux 呈现:展示你的项目!

如何在 JavaScript 中获取 CSS 值

由 Mux 主办的 DEV 全球展示挑战赛:展示你的项目!

有时单靠 CSS 是不够的。你可能需要用 JavaScript 来控制 CSS 值。但是如何在 JavaScript 中获取 CSS 值呢?

事实证明,根据您想要获取的是内联样式还是计算样式,有两种可能的方法。

获取内联样式

内联样式是指以属性形式存在于 HTML 中的样式style

<div class="element" style="font-size: 2em; color: red;">Red hot chili pepper!</div>
Enter fullscreen mode Exit fullscreen mode

要使用内联样式,可以使用该style属性。

const element = document.querySelector('.element');

const fontSize = element.style.fontSize;
console.log(fontSize); // 2em

const color = element.style.color;
console.log(color); // red
Enter fullscreen mode Exit fullscreen mode

获取计算样式

如果你的样式写在 CSS 文件中,你需要获取计算出的样式。为此,你可以使用getComputedStyle.

它需要两个值:

const style = getComputedStyle(Element, pseudoElement);
Enter fullscreen mode Exit fullscreen mode

Element这里指的是你用 . 选择的元素querySelector

pseudoElement这里指的是你要获取的伪元素的字符串(如果有的话)。如果你要选择的不是伪元素,则可以省略此值。

我们来看一个例子来帮助理解。假设你有以下 HTML 和 CSS 代码:

<div class="element"> This is my element </div>
Enter fullscreen mode Exit fullscreen mode
.element {
  background-color: red;
}
Enter fullscreen mode Exit fullscreen mode

首先,你需要使用选中元素querySelector。然后,使用getComputedStyle获取元素样式。

const element = document.querySelector('.element');
const style = getComputedStyle(element);
Enter fullscreen mode Exit fullscreen mode

如果你记录日志style,你应该会看到一个包含所有 CSS 属性及其对应值的对象。

`getComputedStyle` 原始方法返回一个包含所有 CSS 属性及其对应值的对象。


getComputedStyle返回一个包含所有 CSS 属性及其对应值的对象

您也可以在 Chrome 和 Firefox 的开发者工具中看到此对象。

对于 Firefox 开发者工具,请查看“检查器”下的“计算”。

Firefox 开发者工具计算标签页


Firefox 开发者工具计算标签页

在 Chrome 开发者工具中,请查看“元素”选项卡。如果开发者工具窗口较大,您可以在右侧面板中看到计算样式。如果开发者工具窗口较小,您可以在“计算”选项卡下查看。

Chrome 开发者工具计算标签页


Chrome 开发者工具计算标签页

要获取 CSS 属性的值,需要用驼峰命名法书写该属性。

const style = getComputedStyle(element);

const backgroundColor = style.backgroundColor;
console.log(backgroundColor); // rgb(0, 0, 0)
Enter fullscreen mode Exit fullscreen mode

注意:getComputedStyle是只读的。您不能使用 . 设置 CSS 值getComputedStyle

注2:getComputedStyle获取计算出的CSS值。您将从px中获取值,而不是像`\r \n`和`\r\n`这样getComputedStyle的相对单位emrem

从伪元素获取样式

要从伪元素获取样式,需要将伪元素的字符串作为第二个参数传递给它getComputedStyle

<div class="element"> This is my element </div>
Enter fullscreen mode Exit fullscreen mode
.element {
  background-color: red;
}
.element::before {
  content: 'Before pseudo element';
}
Enter fullscreen mode Exit fullscreen mode
const element = document.querySelector('.element');
pseudoElementStyle = getComputedStyle(element, '::before');

console.log(pseudoElementStyle.content); // Before pseudo element
Enter fullscreen mode Exit fullscreen mode

总结

在 JavaScript 中,可以通过两种方法获取 CSS 值:

  1. style物业
  2. getComputedStyle

style属性仅检索内联 CSS 值,而getComputedStylestyle 属性检索计算 CSS 值。

如果这节课对您有所帮助,您或许会喜欢“学习 JavaScript”课程,您将学习如何从零开始构建任何您想要的东西。“学习 JavaScript”课程将于 2018 年 7 月(下周!)开始招生。


感谢阅读。本文最初发布在我的博客上。如果您想阅读更多帮助您成为更优秀的前端开发人员的文章,请订阅我的邮件列表。

文章来源:https://dev.to/zellwk/how-to-get-css-values-in-javascript-32ej