Element: computedStyleMap() 方法
Element 接口的 computedStyleMap() 方法返回一个 StylePropertyMapReadOnly 接口,该接口提供了 CSS 声明块的只读表示形式,是 CSSStyleDeclaration 的替代方案。
语法
computedStyleMap()
参数
无。
返回值
一个 StylePropertyMapReadOnly 对象。
与 Window.getComputedStyle 不同,返回值包含的是 计算值,而不是 解析值。对于大多数属性,这两者是相同的,除了少数与布局相关的属性,它们的解析值是 使用值 而不是计算值。有关详细信息,请参阅 与 getComputedStyle() 的比较 示例。
示例
获取默认样式
我们从一些简单的 HTML 开始:一个带有链接的段落,以及一个定义列表,我们将向其中添加所有 CSS 属性/值对。
<p>
<a href="https://example.com">Link</a>
</p>
<dl id="regurgitation"></dl>
我们添加一些 CSS
a {
--color: red;
color: var(--color);
}
我们添加 JavaScript 来获取我们的链接,并使用 computedStyleMap() 返回所有 CSS 属性值的定义列表。
// get the element
const myElement = document.querySelector("a");
// get the <dl> we'll be populating
const stylesList = document.querySelector("#regurgitation");
// Retrieve all computed styles with computedStyleMap()
const allComputedStyles = myElement.computedStyleMap();
// iterate through the map of all the properties and values, adding a <dt> and <dd> for each
for (const [prop, val] of allComputedStyles) {
// properties
const cssProperty = document.createElement("dt");
cssProperty.appendChild(document.createTextNode(prop));
stylesList.appendChild(cssProperty);
// values
const cssValue = document.createElement("dd");
cssValue.appendChild(document.createTextNode(val));
stylesList.appendChild(cssValue);
}
在 支持 computedStyleMap() 的浏览器 中,您将看到所有 CSS 属性和值的列表。在其他浏览器中,您只会看到一个链接。
您是否意识到一个链接有多少默认 CSS 属性?将 document.querySelector("a") 更新为 document.querySelector("p"),您将注意到 margin-top 和 margin-bottom 的默认计算值有所不同。
与 getComputedStyle() 的比较
Window.getComputedStyle() 返回 解析值,而 computedStyleMap() 返回 计算值。它们通常是相同的,但对于某些属性,解析值是 使用值 而不是计算值。例如,宽度的百分比值在布局后会解析为像素值,因此使用值是像素,而计算值仍然是百分比。
请注意,我们的呈现方式使得这两个 API 看起来比实际情况更相似。computedStyleMap() 包含 CSS 类型化 OM 对象,而 getComputedStyle() 包含字符串。前者以更结构化、更易于处理的方式呈现相同的信息。
在此示例中,width 属性指定为百分比,因此计算值以百分比给出,而解析值以像素给出。height 始终以像素给出。background-color 是命名颜色,但它被计算为 RGB 值。
<div class="container">
<div class="item"></div>
</div>
<pre id="result"></pre>
.container {
width: 200px;
height: 200px;
}
.item {
width: 50%;
height: 100px;
background-color: tomato;
}
const item = document.querySelector(".item");
const result = document.querySelector("#result");
const resolvedValues = getComputedStyle(item);
const computedValues = item.computedStyleMap();
result.textContent = `resolvedValues.width = ${resolvedValues.width}
computedValues.get("width") = ${computedValues.get("width")}
resolvedValues.height = ${resolvedValues.height}
computedValues.get("height") = ${computedValues.get("height")}
resolvedValues.backgroundColor = ${resolvedValues.backgroundColor}
computedValues.get("background-color") = ${computedValues.get(
"background-color",
)}`;
规范
| 规范 |
|---|
| CSS 类型化 OM Level 1 # dom-element-computedstylemap |
浏览器兼容性
加载中…