StylePropertyMapReadOnly: get()-Methode

Limited availability

This feature is not Baseline because it does not work in some of the most widely-used browsers.

Die get()-Methode der StylePropertyMapReadOnly-Schnittstelle gibt ein CSSStyleValue-Objekt für den ersten Wert der angegebenen Eigenschaft zurück.

Syntax

js
get(property)

Parameter

property

Der Name der Eigenschaft, deren Wert abgerufen werden soll.

Rückgabewert

Ein CSSStyleValue-Objekt.

Beispiele

Lassen Sie uns nur einige wenige Eigenschaften und Werte abrufen. Beginnen wir mit der Erstellung eines Links innerhalb eines Absatzes in unserem HTML und fügen wir eine Definitionsliste hinzu, die wir mit JavaScript befüllen werden:

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

Wir fügen ein wenig CSS hinzu, einschließlich einer benutzerdefinierten Eigenschaft und einer vererbbaren Eigenschaft:

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

Wir verwenden das computedStyleMap() des Elements, um ein StylePropertyMapReadOnly-Objekt zurückzugeben. Wir erstellen ein Array von interessanten Eigenschaften und verwenden die get()-Methode von StylePropertyMapReadOnly, um nur diese Werte abzurufen.

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);
}

Spezifikationen

Specification
CSS Typed OM Level 1
# dom-stylepropertymapreadonly-get

Browser-Kompatibilität

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
get

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
No support
No support
See implementation notes.

Siehe auch