Home >Web Front-end >JS Tutorial >How to Retrieve HTML Element Style Values in JavaScript Across Browsers?
Retrieving HTML Element Style Values in JavaScript
For elements with styles defined through the style tag, as illustrated below:
<style> #box { width: 100px; } </style> <div>
To retrieve style values using JavaScript, the element.style property alone won't suffice, as it only provides inline or JavaScript-defined styles.
Computed Styles
We need to access the element's computed style, which represents the actual style applied to it after inheriting from parent elements and accounting for applied CSS rules. In JavaScript, we can obtain computed styles using two methods:
1. DOM Standard (Other Browsers):
document.defaultView.getComputedStyle(element, null).getPropertyValue(propertyName);
2. IE Specific:
element.currentStyle[propertyName];
However, IE uses camelCase property names (e.g., "font-Size") and may return sizes in non-pixel units, while the standard method uses hyphenated property names (e.g., "font-size") and always provides pixel values.
Cross-Browser Solution
To retrieve computed styles in a cross-browser compatible manner, use the following function:
function getStyle(element, property) { var value, defaultView = (element.ownerDocument || document).defaultView; // Sanitize property name for different browsers property = property.replace(/([A-Z])/g, "-").toLowerCase(); if (defaultView && defaultView.getComputedStyle) { return defaultView.getComputedStyle(element, null).getPropertyValue(property); } else if (element.currentStyle) { // Convert camelCase property name to hyphenated property = property.replace(/\-(\w)/g, function(str, letter) { return letter.toUpperCase(); }); value = element.currentStyle[property]; if (/^\d+(em|pt|%|ex)?$/i.test(value)) { return (function(value) { var oldLeft = element.style.left, oldRsLeft = element.runtimeStyle.left; element.runtimeStyle.left = element.currentStyle.left; element.style.left = value || 0; value = element.style.pixelLeft + "px"; element.style.left = oldLeft; element.runtimeStyle.left = oldRsLeft; return value; })(value); } return value; } }
The above is the detailed content of How to Retrieve HTML Element Style Values in JavaScript Across Browsers?. For more information, please follow other related articles on the PHP Chinese website!