Javascript precisely retrieves style attributes (below)

Source: Internet
Author: User

Copy codeThe Code is as follows:
Var rgb2hex = function (rgb ){
Rgb = rgb. match (/^ rgb \ (\ d +), \ s * (\ d +), \ s * (\ d +) \) $ /);
Return "#" + tohex (rgb [1]) + tohex (rgb [2]) + tohex (rgb [3])
}
Var tohex = function (x ){
Var hexDigits = ['0', '1', '2', '3', '4', '5', '6', '7', '8 ', '9', 'A', 'B', 'C', 'D', 'E', 'F'];
Return isNaN (x )? '00': hexDigits [(x-x % 16)/16] + hexDigits [x % 16];
}

We use a regular expression to check whether the regular expression is in rgb format. Instead, we use rgb2hex to convert it. However, if it is red or green, Firefox will not normally convert it to hex format, but IE remains the same. There is no way to make a hash by ourselves, get all the commonly used colors, and then one-to-one matching.
Copy codeThe Code is as follows:
If (style. search (/background | color /)! =-1 ){
Var color = {
Aqua: '# 0ff ',
Black: '#000 ',
Blue: '# 00f ',
Gray: '#808080 ',
Purple: '#800080 ',
Fuchsia: '# f0f ',
Green: '#008000 ',
Lime: '#0f0 ',
Maroon: '#800000 ',
Navy: '#000080 ',
Olive: '#808000 ',
Orange: '# ffa500 ',
Red: '# f00 ',
Silver: '# c0c0c0 ',
Teal: '#008080 ',
Transparent: 'rgba (0, 0, 0, 0 )',
White: '# fff ',
Yellow: '# ff0'
}
If (!! Color [value]) {
Value = color [value]
}
If (value = "inherit "){
Return getStyle (el. parentNode, style );
}
If (/^ rgb \ (\ d +), \ s * (\ d +), \ s * (\ d +) \) $ /. test (value )){
Return rgb2hex (value)
} Else if (/^ #/. test (value )){
Value = value. replace ('#','');
Return "#" + (value. length = 3? Value. replace (/^ (\ w) $/, '$1 $1 $2 $2 $3 $ 3'): value );
}
Return value;
}

Basically, this is the exact value of CSS. Obviously, it still has many shortcomings, but both the layout and common styles are implemented. We also provide a constant q for determining the page rendering mode. For convenience, the method name has the same name as JQuery (only values can be taken, and values cannot be assigned. It will be slowly integrated with my addSheet function later ).
Copy codeThe Code is as follows:
(Function (){
Var isQuirk = (document.doc umentMode )? (Document.doc umentMode = 5 )? True: false: (document. compatMode = "CSS1Compat ")? False: true );
Var isElement = function (el ){
Return !! (El & el. nodeType = 1 );
}
Var propCache = [];
Var propFloat =! + "\ V1 "? 'Stylefloat': 'cssfloat ';
Var camelize = function (attr ){
Return attr. replace (/\-(\ w)/g, function (all, letter ){
Return letter. toUpperCase ();
});
}
Var memorize = function (prop) {// meaning: check out form cache
Return propCache [prop] | (propCache [prop] = prop = 'float '? PropFloat: camelize (prop ));
}
Var getIEOpacity = function (el ){
Var filter;
If (!! Window. XDomainRequest ){
Filter = el. style. filter. match (/progid: DXImageTransform. Microsoft. Alpha \(.? Opacity = (.*).? \)/I );
} Else {
Filter = el. style. filter. match (/alpha \ (opacity = (. *) \)/I );
}
If (filter ){
Var value = parseFloat (filter [1]);
If (! IsNaN (value )){
Return value? Values/100: 0;
}
}
Return 1;
}
Var convertPixelValue = function (el, value ){
Var style = el. style, left = style. left, rsLeft = el. runtimeStyle. left;
El. runtimeStyle. left = el. currentStyle. left;
Style. left = value | 0;
Var px = style. pixelLeft;
Style. left = left; // restore Data
El. runtimeStyle. left = rsLeft; // restore Data
Return px + "px"
}
Var rgb2hex = function (rgb ){
Rgb = rgb. match (/^ rgb \ (\ d +), \ s * (\ d +), \ s * (\ d +) \) $ /);
Return "#" + tohex (rgb [1]) + tohex (rgb [2]) + tohex (rgb [3])
}
Var tohex = function (x ){
Var hexDigits = ['0', '1', '2', '3', '4', '5', '6', '7', '8 ', '9', 'A', 'B', 'C', 'D', 'E', 'F'];
Return isNaN (x )? '00': hexDigits [(x-x % 16)/16] + hexDigits [x % 16];
}
Var getStyle = function (el, style ){
Var value;
If (! + "\ V1 "){
// Specially handle the opacity of IE
If (style = "opacity "){
Return getIEOpacity (el)
}
Value = el. currentStyle [memorize (style)];
// Handle the height and width of IE
If (/^ (height | width) $/. test (style )){
Var values = (style = 'width ')? ['Left', 'right']: ['top', 'bottom '], size = 0;
If (isQuirk ){
Return el [camelize ("offset-" + style)] + "px"
} Else {
Var client = parseFloat (el [camelize ("client-" + style)]),
PaddingA = parseFloat (getStyle (el, "padding-" + values [0]),
PaddingB = parseFloat (getStyle (el, "padding-" + values [1]);
Return (client-paddingA-paddingB) + "px ";
}
}
} Else {
If (style = "float "){
Style = propFloat;
}
Value = document. defaultView. getComputedStyle (el, null). getPropertyValue (style)
}
// All the following parts are used to convert the previous inaccurate values.
If (! /^ \ D + px $/. test (value )){
// Convert measurable values
If (/(em | pt | mm | cm | pc | in | ex | rem | vw | VL | vm | ch | gr) $/. test (value )){
Return convertPixelValue (el, value );
}
// Conversion percentage, excluding the font
If (/% $/. test (value) & style! = "Font-size "){
Return parseFloat (getStyle (el. parentNode, "width") * parseFloat (value)/100 + "px"
}
// Convert the thin medium thick of border
If (/^ (border). + (width) $/. test (style )){
Var s = style. replace ("width", "style "),
B = {
Thin: ["1px", "2px"],
Medium: ["3px", "4px"],
Thick: ["5px", "6px"]
};
If (value = "medium" & getStyle (el, s) = "none "){
Return "0px ";
}
Return !! Window. XDomainRequest? B [value] [0]: B [value] [1];
}
// Convert the auto of margin
If (/^ (margin). +/. test (style) & value = "auto "){
Var father = el. parentNode;
If (/MSIE 6/. test (navigator. userAgent) & getStyle (father, "text-align") = "center "){
Var fatherWidth = parseFloat (getStyle (father, "width ")),
_ Temp = getStyle (father, "position ");
Father. runtimeStyle. postion = "relative ";
Var offsetWidth = el. offsetWidth;
Father. runtimeStyle. postion = _ temp;
Return (fatherWidth-offsetWidth)/2 + "px ";
}
Return "0px ";
}
// Convert top | left | right | bottom's auto
If (/(top | left | right | bottom)/. test (style) & value = "auto "){
Return el. getBoundingClientRect () [style];
}
// Convert the color
If (style. search (/background | color /)! =-1 ){
Var color = {
Aqua: '# 0ff ',
Black: '#000 ',
Blue: '# 00f ',
Gray: '#808080 ',
Purple: '#800080 ',
Fuchsia: '# f0f ',
Green: '#008000 ',
Lime: '#0f0 ',
Maroon: '#800000 ',
Navy: '#000080 ',
Olive: '#808000 ',
Orange: '# ffa500 ',
Red: '# f00 ',
Silver: '# c0c0c0 ',
Teal: '#008080 ',
Transparent: 'rgba (0, 0, 0, 0 )',
White: '# fff ',
Yellow: '# ff0'
}
If (!! Color [value]) {
Value = color [value]
}
If (value = "inherit "){
Return getStyle (el. parentNode, style );
}
If (/^ rgb \ (\ d +), \ s * (\ d +), \ s * (\ d +) \) $ /. test (value )){
Return rgb2hex (value)
} Else if (/^ #/. test (value )){
Value = value. replace ('#','');
Return "#" + (value. length = 3? Value. replace (/^ (\ w) $/, '$1 $1 $2 $2 $3 $ 3'): value );
}
Return value;
}
}
Return value; // For example, 0px
}
Var css = function (){
Var a = arguments;
If (a. length = 1 ){
Return getStyle (this, a [0])
}
}
Var _ = function (el ){
Var el = isElement (el )? El: document. getElementById (el );
Var gene =! El. constructor? El: el. constructor. prototype;
Gene.css = css;
Gene. width = function (){
Return getStyle (this, "width ");
};
Gene. height = function (){
Return getStyle (this, "height ");
};
Return el
}
If (! Window. _) {// to avoid conflicts with JQuery $, I use _ as the unique global variable of the class library.
Window ['_'] = _;
}
_. Q = isQuirk;
})()

The usage is as follows:
Copy codeThe Code is as follows:
Window. onload = function (){
Alert (_ ("ccc" ).css ("background-color "))
Alert (_ ("aaa" ).css ("width "))
Alert (_ (document. body). width ())
};

We can use this Dongxi research project document.bodyand document.doc umentElement.
Copy codeThe Code is as follows:
Function text (){
Var body = document. body, html = document.doc umentElement;
_ ("W1"). innerHTML = _ (body). width ();
_ ("W2"). innerHTML = _ (html). width ();
_ ("H1"). innerHTML = _ (body). height ();
_ ("H2"). innerHTML = _ (html). height ();
_ ("Ml1"). innerHTML = _(body).css ("margin-left ");
_ ("Ml2"). innerHTML = _(html#.css ("margin-left ");
_ ("Mr1"). innerHTML = _(body).css ("margin-right ");
_ ("Mr2"). innerHTML = _(html#.css ("margin-right ");
_ ("Mt1"). innerHTML = _(body).css ("margin-top ");
_ ("Mt2"). innerHTML = _(html#.css ("margin-top ");
_ ("Mb1"). innerHTML = _(body).css ("margin-bottom ");
_ ("Mb2"). innerHTML = _(html#.css ("margin-bottom ");
_ ("Pl1"). innerHTML = _(body).css ("padding-left ");
_ ("Pl2"). innerHTML = _(html#.css ("padding-left ");
_ ("Pr1"). innerHTML = _(body).css ("padding-right ");
_ ("Pr2"). innerHTML = _(html#.css ("padding-right ");
_ ("Bl1"). innerHTML = _(body).css ("border-left-width ");
_ ("Bl2"). innerHTML = _(html#.css ("border-left-width ");
_ ("Br1"). innerHTML = _(body).css ("border-right-width ");
_ ("Br2"). innerHTML = _(html#.css ("border-right-width ");
_ ("Qqq"). innerHTML =! _. Q? "Standard mode": "Strange mode ";
_ ("T1"). innerHTML = _(body).css ("top ");
_ ("T2"). innerHTML = _(html#.css ("top ");
_ ("L1"). innerHTML = _(body).css ("left ");
_ ("L2"). innerHTML = _(html#.css ("left ");
_ ("Ot1"). innerHTML = body. offsetTop;
_ ("Ot2"). innerHTML = html. offsetTop;
_ ("Ol1"). innerHTML = body. offsetLeft;
_ ("Ol2"). innerHTML = html. offsetLeft;
_ ("Ct1"). innerHTML = body. clientTop;
_ ("Ct2"). innerHTML = html. clientTop;
_ ("Cl1"). innerHTML = body. clientLeft;
_ ("Cl2"). innerHTML = html. clientLeft;
_ ("Cw1"). innerHTML = body. clientWidth;
_ ("Cw2"). innerHTML = html. clientWidth;
_ ("Ow1"). innerHTML = body. offsetWidth;
_ ("Ow2"). innerHTML = html. offsetWidth;
_ ("Sw1"). innerHTML = body. scrollWidth;
_ ("Sw2"). innerHTML = html. scrollWidth;
}

<! Doctype html> <ptml dir = "ltr" lang = "zh-CN" id = "html"> <pead> <meta charset = "UTF-8"/> <meta http-equiv = "X-UA-Compatible" content = "IE = 8"> <style type = "text/css"> html, body {border: 0 ;} </style> <title> exact value </title> </pead> <body id = "body"> <table border = "1"> <thead> <th> Test attribute </th> <th> document. body </th> <th> document.doc umentElement </th> </thead> <tbody> <tr> <th> width </th> <td> </td> <td> </tr> <th> height </th> <td> </tr> <tr> <th> margin-left </th> <td> </tr> <th> margin-right </th> <td> </tr> <th> margin-top </th> <td> </td> <td> </tr> <th> margin-bottom </th> <td> </td> </tr> <th> padding-left </th> <td> </tr> <th> padding-right </th> <td> </tr> <th> border-left-width </th> <td> </tr> <th> border-right-width </th> <td> </td> <td> </tr> <th> rendering mode </th> <td colspan = '2'> </td> </tr> <tr> <th> top </th> <td> </tr> <th> left </th> <td> </tr> <th> offsetTop </th> <td> </ td> </tr> <th> offsetLeft </th> <td> </tr> <th> clientTop </th> <td> </tr> <th> clientLeft </th> <td> </td>/ td> </tr> <th> offsetWidth </th> <td> </ tr> <th> clientWidth </th> <td> </tr> <th> scrollWidth </ th> <td> </tr> </tbody> </table> <p> <button type = "button" onclick = "text () "> run the Code </button> </p> <br> <br> </body> </ptml>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
In standard mode, Firefox and other browsers can see that the offsetWidth value is at most 1007, because Firefox's offsetWidth value is not greater than clientWidth, clientWidth does not contain the scroll bar (the width of the scroll bar is fixed to 17px ). In IE, offsetWidth is two more border than clientWidth, and thus the problem is found that 1024-1003-17 = 4 should be generated by two auto, and this auto should be the value of border, the two border are fixed in IE and cannot be modified by the following means.
Copy codeThe Code is as follows:
<Style type = "text/css">
Html {
Border: 0;
}
</Style>

In other words, in standard mode, html of IE is a border with an unchangeable width of 2px. In other words, my program has a BUG that does not correctly display the border of html as 2px and handler.
Let's look at the strange pattern,
Firefox and others do not have the so-called quirks. They can directly look at IE. The mysterious 2px appeared again, and then appeared in clientTop and clientLeft of document. body. What is the concept of css in the clientTop and clientLeft of document. body in the geek mode? Let's take a look at an old figure provided by Microsoft. At that time, IE5 went all over the world and there was no distinction between the standard mode and the strange mode. Therefore, everything in this figure is represented in the strange mode.

It is not hard to see that clientLeft is equivalent to borderLeft, and clientTop is equivalent to borderTop. As for the above border-left-width and border-right-width, do not read them. It is an error, because I didn't consider these two elements in the standard mode and the strange mode at the beginning. Since the border area of document. body is 1024px, where should the html element face be placed ?! Sorry, in the early days of Microsoft, the body element represents the document (a strong evidence is that in the geek mode, the webpage's scroll bar is in the body element ). The pattern, along with the various "standards" promoted by Firefox's losers without market share, is supported by Microsoft's reluctance. Do you think the silly name of documentElement is Microsoft's ?! For Microsoft, it should be called html, which is as concise as document. boy. UmentElement (it is no wonder that the network scene will fail), but the position of the scroll bar does not mean it will change.
Http://www.jb51.net/article/21719.htm

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.