如何在 JavaScript 中获取 CSS 值

2018-11-08  本文已影响0人  月下吴刚_c8c7

在 JavaScript 中获取 CSS 值分两种方式

1 若样式是在内联样式 style中编写的,则要从style中取

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

const element = document.querySelector('.element')
const color = element.style.color

2 若样式是在CSS文件中编写的,则需要获取计算出的样式,使用 getComputedStyle

<div class="element"> This is my element </div>  // html

.element { background-color: red }    // 样式

const element = document.querySelector('.element')
const style = getComputedStyle(element)   // 得到一个对象,里面包含计算过后的属性,从控制台的computed中可以查看
const backgroundColor = style.backgroundColor  // 获取样式值

注意:getComputedStyle 是只读的。您无法使用 getComputedStyle 设置CSS值。

2-2 获取伪类元素的样式

<div class="element"> This is my element </div>

element { background-color: red }
.element::before { content: "Before pseudo element"; }

const element = document.querySelector('.element')
const pseudoElementStyle = getComputedStyle(element, '::before')
console.log(pseudoElementStyle.content) // Before pseudo element

小结

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

style 属性(property),仅检索内联CSS值;

getComputedStyle ,检索计算的CSS值。

上一篇 下一篇

猜你喜欢

热点阅读