A handwritten javascript getStyle function compatible with various browsers (getting element styles)

Source: Internet
Author: User

There have always been many compatibility issues in obtaining calculation styles for HTML elements, and there will be some differences in various browsers. Firefox and webkit (Chrome, Safari) support the W3C standard method: getComputedStyle (), IE6/7/8 does not support standard methods but has private attributes: currentStyle, IE9, and Opera. With these two methods and attributes, most of the requirements can be met.

Copy codeThe Code is as follows:
Var getStyle = function (elem, type ){
Return 'getcomputedstyle' in window? GetComputedStyle (elem, null) [type]: elem. currentStyle [type];
};

However, if currentStyle is used for adaptive width and height, the calculated value cannot be obtained. Only auto can be returned, while getComputedStyle () can return the calculated value. There are several solutions to this problem. I previously thought of using clientWidth/clientHeight to subtract the padding value, so that the calculated width and height can be obtained in browsers that do not support standard methods. A few days ago, situ zhengmei adopted another method. The getBoundingClientRect () method was used to obtain the position of the element on the page. Then right minus left is the width, and bottom minus top is the height. I made some minor changes to his code. The final code is as follows:

Copy codeThe Code 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 '),
// Obtain the calculated width
TWidth = getStyle (test, 'width ');

New Problem: If the width or height of the element uses the em or % unit, the value returned by getComputedStyle () will automatically replace em or % with the px Unit, and currentStyle will not, if the unit is font-size and em is used, 0em is returned in Opera, which is really scary!

Later, I found some unexpected compatibility problems. Today I optimized the original code and handled some common compatibility problems.


In javascript, "-" (a hyphen or a hyphen) represents a minus sign. In CSS, many style attributes have this symbol, such as padding-left and font-size. Therefore, if the following code appears in javascript, this is an error:
Copy codeThe Code is as follows: elem. style. margin-left = "20px ";
The correct statement should be:
Copy codeThe Code is as follows: elem. style. marginLeft = "20px ";
Here, we need to remove the hyphen (-) in CSS and capital the letters that followed the hyphen (-), commonly known as the "camper" method, whether set in javascript or get the CSS style of elements, it should be a camper style. However, many new users who are familiar with CSS and are not familiar with javascript always make such low-level mistakes, the advanced usage of replace can easily replace the strip in the CSS attribute with the camper style.
Copy codeThe Code is as follows: var newProp = prop. replace (/\-(\ w)/g, function ($, $1 ){
Return $1. toUpperCase ();
});

For float, It is a reserved word in javascript. In javascript, other methods are used to set or obtain the float value of an element. In a standard browser, It is cssFloat, in IE6/7/8, it is styleFloat.

If top, right, bottom, and left do not have an explicit value, Some browsers will return an auto when obtaining the value, although the value of auto is a valid CSS property value, but it should be 0px instead of the expected result.

Filters, such as filter: alpha (opacity = 60), are used to set the transparency of elements in IE6/7/8. You can directly Set opacity for standard browsers. IE9 supports both writing methods, I am also compatible with the transparency of the retrieved elements. With opacity, I can obtain the transparency value of all browser elements.

The width and height of the elements obtained in IE6/7/8 have been introduced in the previous article, so we will not repeat them here. Note that if the style of an element is written in style inline or the style attributes have been set using javascript, you can use the following method to obtain the calculation style of the element:
Copy codeThe Code is as follows:
Var height = elem. style. height;

This method is faster than reading the attribute values in getComputedStyle or currentStyle. It should be used first. Of course, the prerequisite is that the style is set by inline writing (using javascript to set the inline style ). The final code optimized is as follows:

Copy codeThe Code is as follows:
Var getStyle = function (elem, p ){
Var rPos =/^ (left | right | top | bottom) $ /,
Ecma = "getComputedStyle" in window,
// Converts a hyphen into a camper, for example, padding-left => paddingLeft
P = p. replace (/\-(\ w)/g, function ($, $1 ){
Return $1. toUpperCase ();
});
// Process float
P = "float "? (Ecma? "CssFloat": "styleFloat"): p;

Return !! Elem. style [p]?
Elem. style [p]:
Ecma?
Function (){
Var val = getComputedStyle (elem, null) [p];
// Process auto for top, right, bottom, and left
If (rPos. test (p) & val = "auto "){
Return "0px ";
}
Return val;
}():
Function (){
Var <a href = "http://wirelesscasinogames.com"> wirelesscasinogames.com </a> val = elem. currentStyle [p];
// Obtain the width and height of an 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 ";
}
// Obtain the transparency of an 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 ";
}
}
// Process auto for top, right, bottom, and left
If (rPos. test (p) & val = "auto "){
Return "0px ";
}
Return val;
}();
};

The following is a call example:

Copy codeThe Code 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>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.