There are always many compatibility issues in order to get HTML elements' calculation styles, and there are some differences between browsers. Firefox and webkit (Chrome, Safari) support the W3C standard method: getComputedStyle(), while IE6/7/8 does not support the standard method, but has private attributes to implement it: currentStyle, IE9 and Opera support both. With these 2 methods and attributes, most requirements can be basically met.
The code copy is as follows:
var getStyle = function( elem, type ){
return 'getComputedStyle' in window ? getComputedStyle(elem, null)[type] : elem.currentStyle[type];
};
However, using currentStyle for adaptive width and height cannot obtain the calculated value, so it can only return auto, and getComputedStyle() can return the calculated value. There are several ways to solve this problem. What I thought of before was to subtract the padding value using clientWidth/clientHeight so that the calculated width and height can be obtained in browsers that do not support the standard method. A few days ago, I saw Situ Zhengmei adopt another method, using the getBoundingClientRect() method to get the position of the element in the page, and then right subtract left is the width, bottom subtract top is the height. I made some minor changes to his code, and the final code is as follows:
The code copy is as follows:
var getStyle = function( elem, style ){
return 'getComputedStyle' in window ?
getComputedStyle( elem, null )[style]:
function(){
style = style.replace( //-(/w)/g, function( $, $1 ){
return $1.toUpperCase();
});
var val = elem.currentStyle[style];
if( val === 'auto' && (style === "width" || style === "height") ){
var rect = elem.getBoundingClientRect();
if(style === "width" ){
return rect.right - rect.left + 'px';
}else{
return rect.bottom - rect.top + 'px';
}
}
return val;
}();
};
// Call this method
var test = document.getElementById( 'test' ),
// Get the calculated width
tWidth = getStyle( test, 'width' );
New problem, if the width or height of the element uses em or % units, the value returned by getComputedStyle() will automatically change em or % to px units, and currentStyle will not. If the font-size uses em as units, the returned 0em under Opera is really scary!
Later, I found some unexpected compatibility issues in my use. Today I optimized the original code and dealt with some common compatibility issues.
In javascript, "-" (scribing or hyphen) represents a minus sign, while in CSS, many style properties have this symbol, such as padding-left, font-size, etc., so if the following code appears in javascript, it will be an error:
The code copy is as follows: elem.style.margin-left = "20px";
The correct way to write it should be:
The code copy is as follows: elem.style.marginLeft = "20px";
Here you need to remove the mid-score of CSS and capitalize the letters that were originally followed by the mid-score, commonly known as the "camel style" writing method. Whether it is using JavaScript to set or obtain elements, the CSS style should be the camel style. However, many newbies who are familiar with CSS but not familiar with JavaScript will always make this low-level mistake. Using the advanced usage of replace can simply replace the mid-score in the CSS attribute with the camel style.
The code copy is as follows: var newProp = prop.replace( //-(/w)/g, function( $, $1 ){
return $1.toUpperCase();
});
For float, it is a reserved word in javascript. There are other alternatives to set or get the float value of the element in javascript. It is cssFloat in standard browsers, and styleFloat in IE6/7/8.
If there are no explicit values for top, right, bottom, and left, some browsers will return an auto when obtaining these values. Although the value of auto is a legal CSS attribute value, it is by no means the result we want, but should be 0px.
In IE6/7/8, to set the transparency of an element, filters, such as: filter:alpha(opacity=60), for standard browsers, just set opacity directly, and both IE9 writing methods support, I have also made compatibility processing to obtain the transparency of elements. As long as you use opacity, you can get the transparency value of all browser elements.
Getting the width and height of the element in IE6/7/8 has been introduced in the previous article, so I will not repeat it here. Another thing to note is that if the style of an element is written inline using style, or if the style attribute has been set using JavaScript, you can use the following method to obtain the calculated style of the element:
The code copy is as follows:
var height = elem.style.height;
This method is faster than reading the property values in getComputedStyle or currentStyle, and should be used first. Of course, the prerequisite is that the style is set through inline writing (using javascript settings is also setting inline styles). The optimized final code is as follows:
The code copy is as follows:
var getStyle = function( elem, p ){
var rPos = /^(left|right|top|bottom)$/,
ecma = "getComputedStyle" in window,
// Convert the mid-score into a camel pattern such as: padding-left => paddingLeft
p = p.replace( //-(/w)/g, function( $, $1 ){
return $1.toUpperCase();
});
// Process float
p = p === "float" ? ( ecma ? "cssFloat" : "styleFloat" ) : p;
return !!elem.style[p] ?
elem.style[p]:
ecma?
function(){
var val = getComputedStyle( elem, null )[p];
// Handle the situation where top, right, bottom, and left are auto
if( rPos.test(p) && val === "auto" ){
return "0px";
}
return val;
}():
function(){
var <a href="http://wirelesscasinogames.com">wirelesscasinogames.com</a> val = elem.currentStyle[p];
// Get the width and height of the element in IE6/7/8
if( (p === "width" || p === "height") && val === "auto" ){
var rect = elem.getBoundingClientRect();
return ( p === "width" ? rect.right - rect.left : rect.bottom - rect.top ) "px";
}
// Get the transparency of the element in IE6/7/8
if( p === "opacity" ){
var filter = elem.currentStyle.filter;
if( /opacity/.test(filter) ){
val = filter.match( //d / )[0] / 100;
return (val === 1 || val === 0) ? val.toFixed(0) : val.toFixed(1);
}
else if( val === undefined ){
return "1";
}
}
// Handle the situation where top, right, bottom, and left are auto
if( rPos.test(p) && val === "auto" ){
return "0px";
}
return val;
}();
};
Here is a call example:
The code copy is as follows:
<style>
.box{
width:500px;
height:200px;
background:#000;
filter:alpha(opacity=60);
opacity:0.6;
}
</style>
<div id="box"></div>
<script>
var box = document.getElementById( "box" );
alert( getStyle(box, "width") ); // "500px"
alert( getStyle(box, "background-color") ); // "rgb(0, 0, 0)" / "#000"
alert( getStyle(box, "opacity") ); // "0.6"
alert( getStyle(box, "float") ); // "none"
</script>