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