This article mainly introduces how to get the css attribute value code in the class of an element in js, if you need it, you can refer to how to use js to obtain the css margin, padding, height, and border in p. You can use document. getElementById ("id"). style. margin to retrieve the data directly. However, you can only obtain the style attributes directly written in the tag. You cannot obtain attributes outside the tag style (such as those in the css file ). The following method can obtain both values.
Example:
When js obtains css attributes, if there is no style in the label, it cannot directly obtain the attributes in css. Therefore, a method is required to do this.
Description of getStyle (obj, attr) Call method: obj is the object, attr is the attribute name must be compatible with the writing method in js (For details, refer to: JS can control the style name writing ).
Js Code
The Code is as follows:
Function getStyle (obj, attr ){
Var ie =! + "\ V1"; // ie6 ~ 8
If (attr = "backgroundPosition") {// IE6 ~ 8. It is not compatible with the backgroundPosition Writing Method and recognizes 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
The Code is as follows:
Js gets the css attribute values in the class of an element.
Css. # box1 {margin: 5px; padding: 5px; height: 100px; width: 200px ;}
Get box1 margin-top
Obtain the padding-top of box1
Get the height of box1
Script
// Obtain the attribute values in the class.
Var ps = document. getElementById ("box1 ");
Function getStyle (obj, attr ){
Var ie =! + "\ V1"; // ie6 ~ 8
If (attr = "backgroundPosition") {// IE6 ~ 8. It is not compatible with the backgroundPosition Writing Method and recognizes 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 (ps, typ ));
}
Script