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

浏览器兼容性

另见