Home >Web Front-end >JS Tutorial >js gets the css attribute value code in the class of an element_javascript skills
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:
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
<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>