Home >Web Front-end >JS Tutorial >Javascript Get Element CSS Style Code Example_Basic Knowledge
There are 4 ways to use CSS to control the page, namely inline style (inline style), inline style, link style, and import style.
Inline style (inline style) is written in the style attribute in the html tag, such as
Inline styles are written in the style tag, such as
The link type is to use the link tag to introduce the css file, for example
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 should be the element style attribute. 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 for which the calculated style is to be obtained. The second parameter can be null or an empty string. , pseudo-classes (such as: before,: after), both parameters are required.
Let’s give an example
#testDiv{
border:1px solid red;
width: 100px;
height: 100px;
Color: red;
}
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.
If you use testDiv.style to obtain style information at this time, 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 attribute.
so, let’s get a general one
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, one thing to note is 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).