乐闻世界logo
搜索文章和话题

Get a CSS value with JavaScript

1个答案

1

Retrieving CSS values in JavaScript is a common requirement, especially when dynamically modifying styles or performing style-related operations. This article introduces two primary methods to retrieve CSS values: using the window.getComputedStyle() function and directly accessing the style property of an element.

Method 1: Using window.getComputedStyle()

The window.getComputedStyle() method retrieves the final computed styles of an element, including inherited styles and styles computed from style sheets. It returns a CSSStyleDeclaration object containing all the final CSS property values of the element.

Example:

Assume the following HTML and CSS code:

html
<!DOCTYPE html> <html lang="en"> <head> <style> .box { width: 100px; height: 100px; background-color: blue; } </style> </head> <body> <div class="box"></div> </body> </html>

To retrieve the background color of this div, use the following JavaScript code:

javascript
let element = document.querySelector('.box'); let style = window.getComputedStyle(element); let bgColor = style.backgroundColor; console.log(bgColor); // Output: rgb(0, 0, 255)

Method 2: Accessing the style Property of an Element

Each DOM element has a style property that contains the inline styles. Note that this method only accesses styles directly set in the element's style attribute.

Example:

Assume the HTML code is slightly modified as follows:

html
<div class="box" style="background-color: red;"></div>

This time, retrieve the background color by accessing the style property:

javascript
let element = document.querySelector('.box'); let bgColor = element.style.backgroundColor; console.log(bgColor); // Output: red

This method applies only to styles directly set via the style attribute. If styles are set via CSS classes, use window.getComputedStyle() instead.

Summary

In practical development, select the appropriate method based on specific requirements to retrieve CSS values. For retrieving the actual displayed styles of an element, use window.getComputedStyle(). For manipulating inline styles, directly access the style property. Both methods have their applicable scenarios, and choosing the right one enhances code efficiency and maintainability.

2024年6月29日 12:07 回复

你的答案