Home > Article > Web Front-end > How Can JavaScript Access CSS Properties of HTML Elements?
CSS Property Extraction with JavaScript
Accessing CSS properties of HTML elements through JavaScript is an essential skill for dynamic web development. Consider the scenario where an external stylesheet, such as "style.css," is linked to a webpage. To manipulate specific CSS properties, it is necessary to retrieve their values using JavaScript.
Options for Reading CSS Properties
There are two primary methods to achieve this:
Example: Extracting the Color Property
Consider the following code snippet:
<code class="javascript">function getStyleProp(elem, prop) { if (window.getComputedStyle) { return window.getComputedStyle(elem, null).getPropertyValue(prop); } else if (elem.currentStyle) { return elem.currentStyle[prop]; // IE } } window.onload = function () { var d = document.createElement("div"); // Create div d.className = "layout"; // Set class = "layout" alert(getStyleProp(d, "color")); // Get property value };</code>
This function takes two parameters: the targeted element and the desired CSS property (e.g., "color"). By creating a temporary div element with the same styling as the target element, the code extracts and returns the specified property value.
Advanced Techniques
To retrieve style properties that exclude inline styles, the getNonInlineStyle() function can be employed:
<code class="javascript">function getNonInlineStyle(elem, prop) { var style = elem.cssText; // Cache the inline style elem.cssText = ""; // Remove all inline styles var inheritedPropValue = getStyle(elem, prop); // Get inherited value elem.cssText = style; // Add the inline style back return inheritedPropValue; }</code>
By temporarily erasing inline styles, this function reveals the inherited property values from the stylesheet.
The above is the detailed content of How Can JavaScript Access CSS Properties of HTML Elements?. For more information, please follow other related articles on the PHP Chinese website!