StylePropertyMapReadOnly: phương thức get()
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
Phương thức get() của giao diện StylePropertyMapReadOnly trả về một đối tượng CSSStyleValue cho giá trị đầu tiên của thuộc tính được chỉ định.
Cú pháp
js
get(property)
Tham số
property-
Tên của thuộc tính cần lấy giá trị.
Giá trị trả về
Một đối tượng CSSStyleValue.
Ví dụ
Hãy lấy một vài thuộc tính và giá trị. Trước tiên, tạo một liên kết bên trong một đoạn văn trong HTML và thêm danh sách định nghĩa để điền bằng JavaScript:
html
<p>
<a href="https://example.com">Link</a>
</p>
<dl id="results"></dl>
Thêm một chút CSS, bao gồm thuộc tính tùy chỉnh và thuộc tính có thể kế thừa:
css
p {
font-weight: bold;
}
a {
--color: red;
color: var(--color);
}
Sử dụng computedStyleMap() của phần tử để trả về một đối tượng StylePropertyMapReadOnly. Tạo một mảng các thuộc tính quan tâm và dùng phương thức get() để chỉ lấy những giá trị đó.
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);
}
Thông số kỹ thuật
| Specification |
|---|
| CSS Typed OM Level 1> # dom-stylepropertymapreadonly-get> |