How to implement javascript to accurately obtain the css attribute value of an element? When dealing with CSS properties of DOM elements, we often encounter a problem: the CSS property value has been defined on the page, but it is empty when obtained. This is because any style sheet file or inline CSS default Style information cannot be reliably reflected in the style attribute. This article introduces you to the method of accurately obtaining the CSS attribute value of a specified element.
Javascript:
Example Source Code
[www.downcodes.com] <script type="text/javascript">
function getStyle(elem, name)
{
//If this attribute exists in style[], it was recently set (and is the current one)
if (elem.style[name])
{
return elem.style[name];
}
// Otherwise, try the IE method
else if (elem.currentStyle)
{
return elem.currentStyle[name];
}
//Or W3C method, if it exists
else if (document.defaultView && document.defaultView.getComputedStyle)
{
//It uses the traditional "text-Align" style rule writing method instead of "textAlign"
name = name.replace(/([AZ])/g,"-$1");
name = name.toLowerCase();
//Get the style object and get the value of the attribute (if it exists)
var s = document.defaultView.getComputedStyle(elem,"");
return s && s.getPropertyValue(name);
//Otherwise, you are using another browser
}
else
{
return null;
}
}
</script>