the styles of HTML nodes are divided into the following types (1) Browser default style (2) Reference style (referencing external CSS file styles, styles defined within style tags) referencing external CSS styles: <link rel= "stylesheet" href= "Css/style.css" type= " Text/css "> Style tag inside:<style> width:100px; </style> (3) inline style (the style defined by the node style property) such as: <div style=" width:100px; " ></div>
Some children's shoes ask: Why do you want to get "non-inline style"?
Sometimes in the use of JS dynamically set the style of an element to consider both style= "Display:none" and the style sheet inside the elem {Display:none} in both cases. As a simple example, if you click a button to show or hide a div element (if the div is hidden by default when the button is clicked, it is hidden). The first thing to get is the default display state of the DIV element, and the style is less accurate if you only get the inline style and the display of the DIV element is set in the style table. Therefore, in addition to the inline style outside the style sheet in the non-inline style also need to get the row.
Here's an example of getting a non-inline style:
HTML code:
<style> *{text-align:Center;}input{Margin-top:30px;padding:10px 20px;}#div1{width:500px;Height:300px;background:Red;margin:10px Auto;}</style><inputtype= "button"value= "Style"ID= "BTN" /><DivID= "Div1"></Div>
The JavaScript code is as follows:
1<script>2 //get non-inline CSS styles3 functionGetStyle (obj,attr) {//gets the non-inline style, where obj is the object and attr is the value4 if(Obj.currentstyle) {//get non-inline styles for IE5 returnobj.currentstyle[attr];6}Else{7 returngetComputedStyle (obj,false) [attr];//for non-IE8 };9 };Ten //Write/Get CSS styles for an object One functionCSS (obj,attr,value) {//object, style, value. To get a style when passing 2 parameters, 3 to set the style A if(Arguments.length = = 2) {//The arguments parameter array, which represents the get CSS style when the parameter array length is 2 - returnGetStyle (OBJ,ATTR);//returns the non-inline style of an object with the GetStyle function above -}Else{ the if(Arguments.length = = 3) {//set a value for the object when passing three arguments -OBJ.STYLE[ATTR] =value; - }; - }; + }; -Window.onload =function(){ + varOdiv = document.getElementById ("Div1"); A varOBTN = document.getElementById ("btn"); atObtn.onclick =function(){ -Alert (GetStyle (odiv, "height"))); -CSS (odiv, "background", "green"); -Alert (CSS (odiv, "width"))); - }; - }; in</script>
JavaScript gets non-inline style/definition style