Js gets the code for the CSS attribute value inside the class of an element

  • 2020-03-30 01:21:13
  • OfStack

How to use js to get margin, padding, height, border and so on of CSS in div. You might say you can get it directly with document.getelementbyid ("id").style.margin. However, you can only get the property of style written directly in the tag, and cannot get the property outside the tag style (such as the property in the CSS file). The following method gets both values.
Example effect diagram is as follows:

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201401/2014116151344508.png" >

 

Js cannot get CSS properties directly if there is no style in the tag, so a method is needed to do this.
GetStyle (obj,attr) call method description: obj for the image,attr for the property name must be compatible with js writing method (you can see: (link: #)).

Js code


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

Complete example test code:
The Html code


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>js Of an element class The inside of the css Attribute values </title>
<style>
#box1{margin:5px;padding:5px;height:100px;width:200px;}
a{border:1px solid #ccc;border-radius:3px;padding:3px 5px;margin:5px 0;display:inline-block;background:#eee;color:#f60;text-decoration:none;font-size:12px;}
a:hover{color:#ff0000;background:#fff;}
</style>
</head>
<body>
<div id="box1">box1 the css.#box1{margin:5px;padding:5px;height:100px;width:200px;}</div>
<a href="javascript:;" onclick="getcss('marginTop')"> To obtain box1 the margin-top</a><br />
<a href="javascript:;" onclick="getcss('paddingTop')"> To obtain box1 the padding-top</a><br />
<a href="javascript:;" onclick="getcss('height')"> To obtain box1 the height</a><br />
<script>
//Gets the value of the attribute in the class
var divs=document.getElementById("box1");
function getStyle(obj,attr){
    var ie = !+"v1";//Simply judge ie6~8
 if(attr=="backgroundPosition"){//IE6~8 is not compatible with backgroundPosition, identify backgroundPositionX/Y
  if(ie){        
   return obj.currentStyle.backgroundPositionX +" "+obj.currentStyle.backgroundPositionY;
     }
 }
 if(obj.currentStyle){
  return obj.currentStyle[attr];
 }
 else{
  return document.defaultView.getComputedStyle(obj,null)[attr];
 }
}
function getcss(typ){
 alert(getStyle(divs,typ));
}
</script>
</body>
</html>


Related articles: