Get Element CSS Property Value as Set (Percent/Em/Px)
Obtaining the CSS property value of an element as specified in the style rules can be challenging, especially when the property has been set in various units. In Google Chrome, the getComputedStyle() method and jQuery's css() method both return the current value in pixels.
Solution: getMatchedStyle Function
To address this issue, a JavaScript function called getMatchedStyle() was developed. It takes an element and a property as arguments and returns the value as it was set in the CSS rules.
function getMatchedStyle(elem, property) { // Check element's own style first var val = elem.style.getPropertyValue(property); if (elem.style.getPropertyPriority(property)) return val; // Get matched CSS rules var rules = getMatchedCSSRules(elem); // Iterate rules in reverse order of priority for (var i = rules.length; i--;) { var r = rules[i]; var important = r.style.getPropertyPriority(property); // Reset value if important or not yet set if (val == null || important) { val = r.style.getPropertyValue(property); if (important) break; } } return val; }
Example
Consider the following HTML code with CSS rules:
<div class="b">div 1</div> <div>
The following JavaScript code uses getMatchedStyle() to obtain the width values for the divs:
var d = document.querySelectorAll('div'); for (var i = 0; i < d.length; ++i) { console.log("div " + (i + 1) + ": " + getMatchedStyle(d[i], 'width')); }
Results:
div 1: 100px div 2: 50% div 3: auto div 4: 44em
The above is the detailed content of How Can I Get the Exact CSS Property Value (Including Units) of an Element in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!