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 |
瀏覽器相容性
載入中…