When needing to obtain the CSS property values of an element as they were initially defined, the function getMatchedStyle offers a solution. This function iterates through the matched CSS rules in descending order of priority, considering both element styles and property importance.
function getMatchedStyle(elem, property){ var val = elem.style.getPropertyValue(property); if(elem.style.getPropertyPriority(property)) return val; var rules = getMatchedCSSRules(elem); for(var i = rules.length; i--;){ var important = r.style.getPropertyPriority(property); if(val == null || important){ val = r.style.getPropertyValue(property); if(important) break; } } return val; }
By considering property importance and element styles, getMatchedStyle accurately returns the CSS property value as set in the stylesheet.
Consider the following HTML and CSS code:
<div class="b">div 1</div> <div>
div { width: 100px; } .d3 { width: auto !important; } div#b { width: 80%; } div#c.c { width: 444px; } x, div.a { width: 50%; } .a { width: 75%; }
Executing the following JavaScript code:
var d = document.querySelectorAll('div'); for(var i = 0; i < d.length; ++i){ console.log("div " + (i+1) + ": " + getMatchedStyle(d[i], 'width')); }
will output:
div 1: 100px div 2: 50% div 3: auto div 4: 44em
This demonstrates the function's ability to accurately extract the set CSS width values of the elements.
The above is the detailed content of How Can I Efficiently Retrieve an Element's Initially Defined CSS Property Values?. For more information, please follow other related articles on the PHP Chinese website!