When a CSS file is linked to a webpage, JavaScript developers may encounter the need to read specific CSS properties of elements.
In this scenario, where a webpage contains a
Option 1: Create and Modify an Element
<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"); d.className = "layout"; alert(getStyleProp(d, "color")); }</code>
Option 2: Manually Parse the Document.styleSheets Object
This option is not recommended unless specifically required to gather all CSS properties defined by a particular selector.
Additionally, to ignore inline style definitions of the current element, utilize the getNonInlineStyle() function:
<code class="javascript">function getNonInlineStyle(elem, prop){ var style = elem.cssText; elem.cssText = ""; var inheritedPropValue = getStyle(elem, prop); elem.cssText = style; return inheritedPropValue; }</code>
The above is the detailed content of How to Retrieve CSS Properties of Webpage Elements Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!