CSS styles are divided into inline and external styles:
1. JavaScript gets the inline style:
You can use Ele.style. " Property name "(If you encounter a property name with"-", you need to use the Hump method, for example Background-color to BackgroundColor);
2. JavaScript gets the external style (getComputedStyle can get the value of the style and can get the CSS of the external style sheet)
To get an external style you can use the browser-provided "window.getComputedStyle (Ele,null)" Here Ele is the object that needs to be manipulated, the second parameter is to specify a pseudo-element match, the regular element is not used, and the direct use of NULL.
But this getcomputedstyle does not support IE9 the following browser, but IE he has his own method of support: Ele.currentstyle;
So in order to achieve the compatibility problem, we can write a general function of our own:
HTML section
<style>
. getdivstyle{
background:red;
}
</style>
<div id= "Js-getdivstyle" class= "Getdivstyle" style= "width:300px;height:300px;" > Testing </div>
JavaScript section
<script>
JS Invocation part
var Getdivstyle = getId ("Js-getdivstyle");
GetStyle (Getdivstyle, "width");
GetStyle (Getdivstyle, "Background-color"); //The properties of this property select Hump or the default plus "-" can be, but not directly use the abbreviation "background"
Encapsulating the Get Style function
function GetStyle (obj,attr) {
if (window.getComputedStyle) {
Return window.getComputedStyle (Obj,null) [attr];
}else{
return obj.currentstyle[attr];
}
}
Encapsulated get Element ID
function GetId (idname) {
return document.getElementById (Idname);
}
</script>
Off Topic
Ele.style. What is the difference between a property name and Ele.csstext and getComputedStyle (obj,null)
1, Ele.style. Property name the style obtained here can get the value of the property, or it can be set to modify him, for example: Ele.style.left = ten + "px";
2, Ele.csstext is actually similar to style, but it is to get multiple CSS styles. For example: Ele.style.cssText = "FONT-SIZE:16PX; Height:250px "is also generated in inline styles.
3, getComputedStyle (obj,null) can only get the value cannot be modified, and the returned CSS is aCSSStyleDeclaration 对象集合。详细见: https://developer.mozilla.org/zh-CN/docs/Web/API/CSSStyleDeclaration
There are several ways to get CSS styles from native JavaScript?