A script-compatible JavaScript GetStyle function for various browsers (get the style of the element) _javascript tips

Source: Internet
Author: User

To get the calculation style of HTML elements there are always many compatibility issues, there are some differences in browsers, Firefox, WebKit (Chrome,safari) to support the standard of the Consortium method: getComputedStyle (), and ie6/7/ 8 does not support standard methods but has private properties to implement: Currentstyle,ie9 and opera two are supported. With these 2 methods and attributes, you can basically meet most of the requirements.

Copy Code code as follows:

var getstyle = function (Elem, type) {
Return to ' getcomputedstyle ' in window? getComputedStyle (Elem, NULL) [type]: Elem.currentstyle[type];
};

However, for adaptive width and height using currentstyle can not get to the calculated value, can only return auto, and getComputedStyle () to return the calculated value, there are several ways to solve this problem. What I had in mind was to subtract the value of the padding with clientwidth/clientheight, so that the width and height of the calculation can be obtained in browsers that do not support standard methods. A few days ago saw Masaki adopted an alternative approach, using the Getboundingclientrect () method to get the element in the page position, and then right minus left is width, bottom minus top is height. I made some minor changes to his code, and the final code was as follows:

Copy Code code as follows:

var getstyle = function (Elem, style) {
Return to ' getcomputedstyle ' in window?
getComputedStyle (Elem, NULL) [style]:
function () {
style = Style.replace (/\-(\w)/g, function ($, $) {
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 '),
Gets the width of the calculation
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, Currentstyle will not, and if font-size uses EM as the unit, In opera, the return of the 0em,opera is really very scary!

Later, in the use of discovery, there are some incompatible compatibility issues, today I have optimized the original code, and some common compatibility issues have been dealt with.


In JavaScript, "-" (underlined or hyphen) represents a minus sign, and in CSS, many style attributes have this symbol, such as Padding-left, Font-size, and so on, so if the following code appears in JavaScript it is an error:

Copy Code code as follows:
Elem.style.margin-left = "20px";

The correct wording should be:
Copy Code code as follows:
Elem.style.marginLeft = "20px";

Here you need to remove the middle of the CSS and the original immediately after the underlined letter capitalized, commonly known as the "hump-style" style, whether the use of JavaScript settings or get elements of CSS styles should be the hump-style writing. But many novice friends who are familiar with CSS and unfamiliar with JavaScript are always making this kind of low-level error, and using the advanced usage of replace can easily replace the underscore in the CSS attribute with the hump style.
Copy Code code as follows:
var newprop = Prop.replace (/\-(\w)/g, function ($, $) {
return $1.touppercase ();
});

For float, a reserved word in JavaScript, a value that sets or gets the float of an element in JavaScript, has other alternatives, is cssfloat in standard browsers, and stylefloat in IE6/7/8.

If top, right, bottom, and left do not have an explicit value, some browsers will return an auto when you get these values, although the auto value is a legitimate CSS property value, but not the result we want, but 0px.

To set the transparency of an element in IE6/7/8 you need to use a filter, such as: Filter:alpha (opacity=60), for standard browser directly set opacity, IE9 two ways to support, I have to get the transparency of the elements also do a compatibility process, You can get the value of the transparency of all browser elements as long as you use opacity.

Getting the width and height of the elements in the IE6/7/8 has been introduced in the previous article, and this is not repeated here. Another thing to note is that if the style of the element is written inline with style, or if the style has been set using JavaScript, you can get the calculated style of the element using the following method:

Copy Code code as follows:

var height = elem.style.height;

This method is faster than reading the property values in getComputedStyle or currentstyle, and should be used preferentially, of course, if the style is set by inline notation (also set inline style using JavaScript settings). The optimized final code is as follows:

Copy Code code as follows:

var getstyle = function (Elem, p) {
var rpos =/^ (left|right|top|bottom) $/,
ECMA = "getComputedStyle" in window,
Convert the underline to hump type: Padding-left => paddingleft
p = p.replace (/\-(\w)/g, function ($, $) {
return $1.touppercase ();
});
To process a float
p = p = = "float"? (ECMA?) "Cssfloat": "Stylefloat"): P;

Return!! ELEM.STYLE[P]?
ELEM.STYLE[P]:
ECMA?
function () {
var val = getcomputedstyle (Elem, NULL) [P];
Handle top, right, bottom, left as 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];
Gets 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";
}
Get 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";
}
}
Handle top, right, bottom, left as auto
if (Rpos.test (p) && val = = "Auto") {
return "0px";
}
return Val;
}();
};

Here is the call example:

Copy Code code 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.