如何在 JavaScript 中获取 CSS 值

在 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值。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML标准。 注意:讲述HT...
    kismetajun阅读 27,750评论 1 45
  • 概要 64学时 3.5学分 章节安排 电子商务网站概况 HTML5+CSS3 JavaScript Node 电子...
    阿啊阿吖丁阅读 9,342评论 0 3
  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 13,815评论 1 92
  • 原文: https://github.com/ecomfe/spec/blob/master/javascript...
    zock阅读 3,408评论 2 36
  • 轻装前行---别人可以,你也一定可以。 趁着有空我又重新做了人生十一问,我想要的越来越清晰,可我看到的是一座大山挡...
    整理师秋竹阅读 130评论 0 0