How to obtain the MARGIN, PADDING, Height, Border, etc. in DIV. You may say that you can directly obtain it with Document.GetelementByid ("ID"). Style.margin. But what you said can only obtain the attributes written directly in the label, and the attributes outside the label Style cannot be obtained (such as the attributes in the CSS file). The following methods can be obtained.
The instance renderings are as follows:
JS cannot directly obtain the attributes in the CSS when obtaining the CSS attribute, so you need one method to do this.
GetStyle (OBJ, ATTR) calling method description: OBJ is the object, ATTR is a compatibility of the attribute name must be compatible with the writing of JS (refer to: JS can control the style of the style).
Js code
Copy code code as follows:
Function GetStyle (Obj, Attr) {
var IE =!+"/V1"; // Simple judgment IE6 ~ 8
Iftr == "Backgroundposition") {// IE6 ~ 8 is not compatible with BackgroundPosition writing to identify Backgroundpositionx/Y
if (ie) {{
Return obj.currenTSTYLE.BACKGROUNDPOSITIONX +" +Obj.CurrenTSTYLE.BACKROUNDPOSITIONY;
}
}
if (obj.currentStyle) {
Return obj.currenTSTyle [Attr];
}
else {
Return document.defaultView.getComputedStyle (obj, null) [attr];
}
}
Full instance test code:
HTML code
Copy code code as follows:
<! Doctype HTML PUBLIC "-// W3C // DTD XHTML 1.0 Transitional // EN" http://www.w3.org/xhtml1/dtddml1-transitationAl.dtd ">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv = "content-type" content = "text /html; charset = gb2312" /> />
<Title> JS Get the CSS attribute value in the Class of a certain 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;#f60; text-de Corating: None; FONT-SIZE : 12px;}
A: Hover {color:#ff0000; background: #fff;}
</style>
</head>
<body>
<div ID = "Box1"> Box1's CSS.#BOX1 {Margin: 5px; Padding: 5px; Height: 100px; width: 200px;} </div>
<A href = "javascript:;" Onclick = "Getcss ('Margintop')"> Get the Margin-TOP </a> <br /> <br />
<A href = "javascript:;" Onclick = "Getcss ('Paddingtop')"> Get the Padding-TOP </a> < /> <br />
<A href = "javascript:;" Onclick = "Getcss ('Height')"> Get the height </a> <br />
<script>
// Get the attribute value in class
var divs = document.GetelementByid ("Box1");
Function GetStyle (Obj, Attr) {
var IE =!+"/V1"; // Simple judgment IE6 ~ 8
Iftr == "Backgroundposition") {// IE6 ~ 8 is not compatible with BackgroundPosition writing to identify Backgroundpositionx/Y
if (ie) {{
Return obj.currenTSTYLE.BACKGROUNDPOSITIONX +" +Obj.CurrenTSTYLE.BACKROUNDPOSITIONY;
}
}
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>