Home >Web Front-end >JS Tutorial >How to Get an HTML Element's Style Values Across Different Browsers?
How to Retrieve an HTML Element's Style Values in JavaScript
Retrieving style values from HTML elements is essential for manipulating elements' appearance dynamically. While setting styles using JavaScript is straightforward, accessing styles defined in style tags can be tricky.
Cross-Browser Considerations
Accessing element styles requires a cross-browser approach. Internet Explorer uses its own property, currentStyle, while other browsers follow the W3C standard and utilize document.defaultView.getComputedStyle.
Custom Cross-Browser Function
To handle cross-browser inconsistencies, a custom function is often employed:
function getStyle(el, styleProp) { var value, defaultView = (el.ownerDocument || document).defaultView; // W3C standard way: if (defaultView && defaultView.getComputedStyle) { // sanitize property name to css notation 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; } }
Usage
To retrieve the style property of an element:
var element = document.getElementById("box"); var width = getStyle(element, "width");
Current Considerations
The above function may not handle all edge cases, particularly for colors where the returned value may differ between IE and other browsers.
The above is the detailed content of How to Get an HTML Element's Style Values Across Different Browsers?. For more information, please follow other related articles on the PHP Chinese website!