StylePropertyMapReadOnly
StylePropertyMapReadOnly 接口是 CSS 类型的对象模型 API 的一部分,它提供了 CSS 声明块的只读表示,这是 CSSStyleDeclaration 的一种替代方案。可以使用 Element.computedStyleMap() 来获取此接口的实例。
实例属性
StylePropertyMapReadOnly.size-
返回一个无符号长整型整数,表示
StylePropertyMapReadOnly对象的大小。
实例方法
StylePropertyMapReadOnly.entries()-
返回给定对象的自身可枚举属性的
[key, value]对数组,其顺序与for...in循环提供的顺序相同(区别在于 for-in 循环还会枚举原型链上的属性)。 StylePropertyMapReadOnly.forEach()-
对
StylePropertyMapReadOnly的每个元素执行一次提供的函数。 StylePropertyMapReadOnly.get()-
返回指定属性的值。
StylePropertyMapReadOnly.getAll()-
返回一个包含指定属性值的
CSSStyleValue对象数组。 StylePropertyMapReadOnly.has()-
指示指定的属性是否存在于
StylePropertyMapReadOnly对象中。 StylePropertyMapReadOnly.keys()-
返回一个包含
StylePropertyMapReadOnly中每个项目键的新数组迭代器。 StylePropertyMapReadOnly.values()-
返回一个包含
StylePropertyMapReadOnly对象中每个索引值的新的数组迭代器。
示例
我们必须有一个要观察的元素
html
<p>
This is a paragraph with some text. We can add some CSS, or not. The style map
will include all the default and inherited CSS property values.
</p>
<dl id="output"></dl>
我们添加了一些 CSS 和自定义属性,以更好地演示输出
css
p {
--some-variable: 1.6em;
--some-other-variable: translateX(33vw);
--another-variable: 42;
line-height: var(--some-variable);
}
我们添加了 JavaScript 来抓取我们的段落,并使用 Element.computedStyleMap() 返回所有默认 CSS 属性值的定义列表。
js
// get the element
const myElement = document.querySelector("p");
// get the <dl> we'll be populating
const stylesList = document.querySelector("#output");
// Retrieve all computed styles with computedStyleMap()
const stylePropertyMap = myElement.computedStyleMap();
// iterate through the map of all the properties and values, adding a <dt> and <dd> for each
for (const [prop, val] of stylePropertyMap) {
// properties
const cssProperty = document.createElement("dt");
cssProperty.innerText = prop;
stylesList.appendChild(cssProperty);
// values
const cssValue = document.createElement("dd");
cssValue.innerText = val;
stylesList.appendChild(cssValue);
}
规范
| 规范 |
|---|
| CSS 类型化 OM Level 1 # the-stylepropertymap |
浏览器兼容性
加载中…