StylePropertyMapReadOnly: get() 方法

可用性有限

此特性不是基線特性,因為它在一些最廣泛使用的瀏覽器中不起作用。

StylePropertyMapReadOnly 介面的 get() 方法返回指定屬性的第一個值的 CSSStyleValue 物件。

語法

js
get(property)

引數

property(屬性)

要檢索其值的屬性名稱。

返回值

一個 CSSStyleValue 物件。

示例

讓我們獲取一些屬性和值。首先,在 HTML 中建立一個段落中的連結,並新增一個我們將用 JavaScript 填充的定義列表

html
<p>
  <a href="https://example.com">Link</a>
</p>
<dl id="results"></dl>

我們新增一些 CSS,包括一個自定義屬性和一個可繼承屬性

css
p {
  font-weight: bold;
}
a {
  --color: red;
  color: var(--color);
}

我們使用 Element 的 computedStyleMap() 返回一個 StylePropertyMapReadOnly 物件。我們建立一個感興趣的屬性陣列,並使用 StylePropertyMapReadOnly 的 get() 方法來僅獲取這些值。

js
// get the element
const myElement = document.querySelector("a");

// Retrieve all computed styles with computedStyleMap()
const styleMap = myElement.computedStyleMap();

// get the <dl> we'll be populating
const stylesList = document.querySelector("#results");

// array of properties we're interested in
const ofInterest = ["font-weight", "border-left-color", "color", "--color"];

// iterate over our properties of interest
for (const property of ofInterest) {
  // properties
  const cssProperty = document.createElement("dt");
  cssProperty.innerText = property;
  stylesList.appendChild(cssProperty);

  // values
  const cssValue = document.createElement("dd");
  // use get() to find the value
  cssValue.innerText = styleMap.get(property);
  stylesList.appendChild(cssValue);
}

規範

規範
CSS 型別化 OM Level 1
# dom-stylepropertymapreadonly-get

瀏覽器相容性

另見