With JS how to get the CSS in the div margin, padding, height, border and so on. You may say you can use document.getElementById ("id") directly. Style.margin get. But you said you can only get properties of the style written directly in the label, you cannot get properties outside of the label style, such as properties in a CSS file. The following method is available for both values.
The example effect diagram is as follows:
JS in the acquisition of CSS Properties, if the label has no style can not directly get the attributes in the CSS, so need a way to do this.
GetStyle (obj,attr) Call method Description: obj for the image, attr for attribute names must be compatible with the writing in JS (you can refer to: JS can control the style of the name).
JS Code
Copy Code code as follows:
function GetStyle (obj,attr) {
var ie =!+ "\v1";/Simple Judgment ie6~8
if (attr== "backgroundposition") {//ie6~8 incompatible backgroundposition notation, 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 Instance test code:
HTML code
Copy Code code as follows:
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<meta http-equiv= "Content-type" content= "text/html; charset=gb2312 "/>
<title>js gets the CSS attribute value in the class of an element </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>
<body>
<div id= "Box1" >box1 css. #box1 {margin:5px;padding:5px;height:100px;width:200px;} </div>
<a href= "javascript:;" onclick= "getcss (' margintop ')" > Get box1 margin-top</a><br/
<a href= "javascript:;" onclick= "getcss (' paddingtop ')" > Get box1 padding-top</a><br;
<a href= "javascript:;" onclick= "getcss (' height ')" > Get box1 height</a><br;
<script>
Gets the property value inside the class
var Divs=document.getelementbyid ("Box1");
function GetStyle (obj,attr) {
var ie =!+ "\v1";/Simple Judgment ie6~8
if (attr== "backgroundposition") {//ie6~8 incompatible backgroundposition notation, 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>