Home >Web Front-end >JS Tutorial >js gets the css attribute value code in the class of an element_javascript skills

js gets the css attribute value code in the class of an element_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:03:361185browse

How to use js to get the margin, padding, height, border, etc. of the css in a div. You may say that you can get it directly using document.getElementById("id").style.margin. But what you said can only get the attributes of the style written directly in the tag, and you cannot get the attributes outside the style tag (such as attributes in the css file). Both values ​​can be obtained by the following method.
The example rendering is as follows:

js gets the css attribute value code in the class of an element_javascript skills

When js obtains css attributes, if there is no style in the tag, it cannot directly obtain the attributes in css, so a method is needed to do this.
getStyle(obj,attr) Calling method description: obj is the object, attr is the attribute name and must be compatible with the writing method in js (refer to: JS can control the writing method of the style name).

Js code

Copy code The code is as follows:

function getStyle(obj,attr) {
var ie = ! "v1";//Simple judgment ie6~8
if(attr=="backgroundPosition"){//IE6~8 is not compatible with backgroundPosition writing, identify backgroundPositionX/Y
if (ie){                                                                                                                                                                                                  return obj.currentStyle.
}
else{
return document.defaultView.getComputedStyle(obj,null)[attr];
}
}




Complete example test code: Html code


Copy code

The code is as follows:
js gets the css attribute value in the class of an element




box1's css.#box1{margin:5px;padding:5px;height:100px;width:200px;}

Get the margin-top of box1

Get the padding-top of box1
Get the height of box1


<script><br>//Get the attribute value in class<br>var divs=document.getElementById("box1");<br>function getStyle(obj,attr){</p> var ie = ! "v1";//Simple judgment ie6~8<p> if(attr=="backgroundPosition"){//IE6~8 is not compatible with backgroundPosition writing method, identify backgroundPositionX/Y<br> if(ie){                                                      return obj.currentStyle.backgroundPositionX " " obj.currentStyle.backgroundPositionY;<br> }<br> }<br> if(obj.currentStyle){<br> return obj.currentStyle[attr];<br> }<br> else{<br> return document.defaultView.getComputedStyle(obj,null)[attr];<br> }<br>}<br>function getcss(typ){<br> alert(getStyle(divs,typ)); <br>}<br></script>




Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn