js獲取某元素的class裡面的css屬性值程式碼(轉)
阿新 • • 發佈:2019-01-07
這篇文章主要介紹了js獲取某元素的class裡面的css屬性值程式碼,有需要的朋友可以參考一下
用js如何獲取div中css的 margin、padding、height、border等。你可能說可以直接用document.getElementById("id").style.margin獲取。但是你說的只能獲取直接在標籤中寫的style的屬性,無法獲取標籤style外的屬性(如css檔案中的屬性)。而下面方法則兩者值都可以獲取。
例項效果圖如下:
js在獲取css屬性時如果標籤中無style則無法直接獲取css中的屬性,所以需要一個方法可以做到這點。
getStyle(obj,attr) 呼叫方法說明:obj為對像,attr為屬性名必須相容js中的寫法(可以參考: JS可以控制樣式的名稱寫法)。
Js程式碼
完整例項測試程式碼:function getStyle(obj,attr){ var ie = !+"\v1";//簡單判斷ie6~8 if(attr=="backgroundPosition"){//IE6~8不相容backgroundPosition寫法,識別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]; } }
Html程式碼
<!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獲取某元素的class裡面的css屬性值</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的css.#box1{margin:5px;padding:5px;height:100px;width:200px;}</div> <a href="javascript:;" onclick="getcss('marginTop')">獲取box1的margin-top</a><br /> <a href="javascript:;" onclick="getcss('paddingTop')">獲取box1的padding-top</a><br /> <a href="javascript:;" onclick="getcss('height')">獲取box1的height</a><br /> <script> //獲取class裡面的屬性值 var divs=document.getElementById("box1"); function getStyle(obj,attr){ var ie = !+"\v1";//簡單判斷ie6~8 if(attr=="backgroundPosition"){//IE6~8不相容backgroundPosition寫法,識別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>