CSS Object Model 之 CSSStyleDeclaration

588 阅读1分钟

CSSStyleDeclaration 是什么

css 样式声明对象,CSSStyleDeclaration 对象表示一个 CSS 属性-值(property-value)对的集合。

从哪里知道 CSSStyleDeclaration

window.CSSStyleDeclaration || CSSStyleDeclaration 是从哪里返回的呢?

我们直接从 dom 节点引用的 style属性,就能拿到 CSSStyleDeclaration, 它是一个大的对象。

document.getElementsByTagName('div')[0].style // 返回的是内联样式
document.getElementsByTagName('div')[0].styleSheets // CSSStyleDeclaration

在通过 Object.keys 我们知道大概哟 514 个 CSS 属性。

属性

  • cssText
  • length
  • parentRule

dom 操作

<h1 style="color: red; font-size: 50px;">length 属性</h1>
var elmnt = document.getElementsByTagName("h1")[0]; //
var x = elmnt.style.cssText; // ''
var len = elmnt.style.length; // 

方法

  • getPropertyPriority()
  • getPropertyValue()
  • item()
  • removeProperty()
  • setProperty()

获取 css 的样式表

document.styleSheets 集合 StyleSheetList, 这是列表,上面是样式声明

参考