There are four ways to use CSS to control the page, namely inline style (inline style), inline style, link style, and imported style.
Inline styles (inline styles) are written in the style attribute in the html tag, such as <div></div>
Inline styles are written in the style tag, such as <style type="text/css">div{width:100px; height:100px}</style>
The link type is to use the link tag to introduce the css file, such as <link href="test.css" type="text/css" rel="stylesheet" />
The import method is to use import to introduce css files, such as @import url("test.css")
If you want to use JavaScript to obtain the style information of an element, the first thing that comes to mind is the style attribute of the element. However, the style attribute of an 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 calculated style of the element to obtain the style information of the element.
Use the getComputedStyle method of the window object to get the calculated style of an element. This method has 2 parameters. The first parameter is the element whose calculated style is to be obtained. The second parameter can be null, empty string, or pseudo-class (such as: before,:after), both parameters are required.
Let's give an example
<style type="text/css">
#testDiv{
border:1px solid red;
width: 100px;
height: 100px;
color: red;
}
</style>
<div id="testDiv"></div>
var testDiv = document.getElementById("testDiv");
var computedStyle = window.getComputedStyle(testDiv, "");
var width = computedStyle.width; //100px
var height = computedStyle.height; //100px
var color = computedStyle.color; //rgb(255, 0, 0)
[/code]
Note: The obtained color attributes are all returned in rgb(#,#,#) format.
At this time, if you use testDiv.style to obtain style information, testDiv.style.width will definitely be empty.
The getComputedStyle method is not implemented in IE8 and earlier versions, but each element in IE has its own currentStyle property.
So, let’s get a general one
Copy the code code as follows:
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, please note that the calculated style of an element is read-only. If you want to set the style of an element, you must use the style attribute of the element (this is the real purpose of the style attribute of the element).