首页 > 代码库 > js获取非行间样式或定义样式

js获取非行间样式或定义样式

 1 <!--DOCTYPE html--> 2 <html> 3 <head> 4 <meta charset="utf-8" /> 5 <style> 6 *{ text-align:center;} 7 input{ margin-top:30px; padding:10px 20px;} 8 #div1{ width:500px; height:300px; background:red; margin:10px auto;} 9 </style>10 </head>11 <body>12 <input type="button" value="style" id="btn" />13 <div id="div1"></div>14  15 <script>16 //获取非行间css样式17 function getStyle(obj,attr){    //获取非行间样式,obj是对象,attr是值18     if(obj.currentStyle){   //针对ie获取非行间样式19         return obj.currentStyle[attr];20     }else{21         return getComputedStyle(obj,false)[attr];   //针对非ie22     };23 };24 //为对象写入/获取css样式25 function css(obj,attr,value){   //对象,样式,值。传2个参数的时候为获取样式,3个是设置样式26     if(arguments.length == 2){  //arguments参数数组,当参数数组长度为2时表示获取css样式27         return getStyle(obj,attr);  //返回对象的非行间样式用上面的getStyle函数28     }else{29         if(arguments.length == 3){  //当传三个参数的时候为设置对象的某个值30             obj.style[attr] = value;31         };32     };33 };34 window.onload = function(){35     var oDiv = document.getElementById("div1");36     var oBtn = document.getElementById("btn");37     oBtn.onclick = function(){38         alert(getStyle(oDiv,"height"));39         css(oDiv,"background","green");40         alert(css(oDiv,"width"));41     };42 };43 </script>44 </body>45 </html>