Accessing HTML Element Style Values in JavaScript
One may encounter a need to retrieve the styles from an HTML element that has been defined in the CSS stylesheet. For instance, consider the following HTML and CSS code:
<style> #box { width: 100px; } </style> <body> <div>
Using only pure JavaScript without any libraries, how can you retrieve the value for the width property? The following attempts often result in receiving blank values:
alert(document.getElementById("box").style.width); alert(document.getElementById("box").style.getPropertyValue("width"));
These attempts fail because they only work with inline styles defined within the element's style attribute. To retrieve computed styles, a different approach is needed.
Cross-Browser Compatibility
Accessing computed styles presents a challenge due to differences between browsers. Internet Explorer uses the element.currentStyle property, while other browsers follow the DOM Level 2 standard with document.defaultView.getComputedStyle. Additionally, IE handles property names with two or more words differently, using camelCase (e.g., "maxHeight"). Other browsers expect dashes to separate words (e.g., "max-height").
Cross-Browser Function
To address these cross-browser differences, the following function can be employed:
function getStyle(el, styleProp) { var value, defaultView = (el.ownerDocument || document).defaultView; if (defaultView && defaultView.getComputedStyle) { styleProp = styleProp.replace(/([A-Z])/g, "-").toLowerCase(); return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp); } else if (el.currentStyle) { styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) { return letter.toUpperCase(); }); value = el.currentStyle[styleProp]; 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; } }
This function provides cross-browser compatibility for accessing computed styles, handling both standard and IE-specific behavior. Note that it may not handle all cases, such as colors, which are returned differently by different browsers.
The above is the detailed content of How to Retrieve an HTML Element's CSS Style Value Using Pure JavaScript?. For more information, please follow other related articles on the PHP Chinese website!