首页 > 代码库 > 兼容性获取style样式

兼容性获取style样式

 1 封装getStyle (获取样式currentStyle getComputedStyle兼容处理)
 2 <script type="text/javascript">
 3  4 
 5 
 6 function getStyle(obj, attr)
 7 {
 8  if(obj.currentStyle)
 9  {
10   return obj.currentStyle[attr];
11  }
12  else
13  {
14   return getComputedStyle(obj, false)[attr];
15  }
16 }
17 
18 window.onload=function ()
19 {
20  var oDiv=document.getElementById(div1);
21  
22  alert(getStyle(oDiv, backgroundColor));
23 }
24 </script>
25 
26  
27 
28 <div id="div1"></div>
29 
30  
31 
32  
33 
34 //获取样式简洁版
35 function getStyle(obj, attr) {
36     return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj, false)[attr];
37 }
38 //opacity 设置透明度
39 function setOpacity(elem, value) {
40     elem.filters ? elem.style.filter = alpha(opacity= + value + ) : elem.style.opacity = value / 100;
41 }
42 
43 
44 //完美版
45 function css(obj, attr, value){
46     switch (arguments.length){
47         case 2:
48             if(typeof arguments[1] == "object"){
49                 for (var i in attr) i == "opacity" ? (obj.style["filter"] = "alpha(opacity=" + attr[i] + ")", obj.style[i] = attr[i] / 100) : obj.style[i] = attr[i];
50             }else{
51                 return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj, null)[attr]
52             }
53             break;
54         case 3:
55             attr == "opacity" ? (obj.style["filter"] = "alpha(opacity=" + value + ")", obj.style[attr] = value / 100) : obj.style[attr] = value;
56             break;
57     }
58 };

 

兼容性获取style样式