Javascript gets the code sample for the element CSS style

  • 2020-03-30 00:02:43
  • OfStack


There are four ways to use CSS to control a page: inline, inline, link-in, and lead-in.

Inline styles are written in the style attribute of an HTML tag, such as < Div style = "width: 100 px; Height: 100 px;" > < / div>

Inline styles are written in the style tag, for example < Style type = "text/CSS" > Div {width: 100 px; Height: 100 px} < / style>

Linking means using the link tag to introduce CSS files, for example < Link href="test.css" type="text/ CSS "rel="stylesheet" />

Import means importing a CSS file with an import, such as the @import url("test.css")


If you want to get style information for an element using javascript, the first thing that comes to mind is the style attribute of the element. However, the style attribute of the element only represents the inline style of the element. If part of the style information of an element is written in the inline style and part is written in the external CSS file, the complete style information of the element cannot be obtained through the style attribute. Therefore, you need to use the element's computational style to get the element's style information.

The getComputedStyle method of the window object is used to get the computation style of an element. This method has two parameters, the first parameter is the element to get the computation style, and the second parameter can be null, an empty string, or a pseudo-class (such as :before,:after), both of which are required.

For example

< Style type = "text/CSS" >

# testDiv {

Border: 1 px solid red;

Width: 100 px;

Height: 100 px;

Color: red;

}

< / style>

< Div id = "testDiv" > < / div>

Var testDiv = document. GetElementById (" testDiv ");

Var computedStyle = window.getcomputedstyle (testDiv, "");

Var width = computedStyle. Width; / / 100 px

Var height = computedStyle. Height; / / 100 px

Var color = computedStyle. Color; / / RGB (255, 0, 0)
[/ code]

Note: the color properties obtained are returned in RGB (#,#,#) format.

At this time, if you use testdiv.style to get the style information, such as testdiv.style.width is definitely empty.

 

The getComputedStyle method is not implemented in IE8 and earlier versions, but each element in IE has its own currentStyle attribute.

So, a general purpose one


var testDiv = document.getElementById("testDiv");
var styleInfo = window.getComputedStyle ? window.getComputedStyle(testDiv, "") : testDiv.currentStyle;
var width = styleInfo.width;  //100px;
var height = styleInfo.height;  //100px;
var color = styleInfo.color;  // rgb(255, 0, 0)

 

Finally, note that elements are evaluated in a read-only fashion, and if you want to set the style of an element, you have to use the element's style attribute (which is what the element's style attribute is really for).


Related articles: