Home >Web Front-end >CSS Tutorial >How Can I Retrieve Computed Style Values for HTML Elements Across Different Browsers in JavaScript?
Extracting HTML Element Style Values in Javascript
To acquire style attributes assigned via inline CSS or style tags, it's necessary to fetch the computed style rather than the element's style property alone. This involves utilizing cross-browser compatible methods like document.defaultView.getComputedStyle and element.currentStyle.
Cross-Browser Compatibility
Internet Explorer employs element.currentStyle while other browsers adhere to the standard document.defaultView.getComputedStyle method. Note that IE expects CSS property names in camelCase format, while the standard format employs dashes.
Unit Conversion on IE
IE returns sizes in original units, while the standard method always converts to pixels. The provided getStyle function accounts for this by converting units on IE if necessary.
Color Format
The standard method returns color values in RGB notation, whereas IE displays them as defined. The getStyle function may not handle all cases perfectly, particularly for color formats.
Custom Function for Computed Style Retrieval
The following getStyle function provides a cross-browser approach to retrieving computed styles:
function getStyle(el, styleProp) { var value, defaultView = (el.ownerDocument || document).defaultView; // W3C standard way: if (defaultView && defaultView.getComputedStyle) { // sanitize property name to css notation // (hypen separated words eg. font-Size) styleProp = styleProp.replace(/([A-Z])/g, "-").toLowerCase(); return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp); } else if (el.currentStyle) { // IE // sanitize property name to camelCase styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) { return letter.toUpperCase(); }); value = el.currentStyle[styleProp]; // convert other units to pixels on IE if (/^\d+(em|pt|%|ex)?$/i.test(value)) { return (function(value) { var oldLeft = el.style.left, oldRsLeft = el.runtimeStyle.left; el.runtimeStyle.left = el.currentStyle.left; el.style.left = value || 0; value = el.style.pixelLeft + "px"; el.style.left = oldLeft; el.runtimeStyle.left = oldRsLeft; return value; })(value); } return value; } }
The above is the detailed content of How Can I Retrieve Computed Style Values for HTML Elements Across Different Browsers in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!