获取和设置样式的css函数

跨浏览器的简易获取和设置元素样式的函数,函数处理了opacity和float的兼容性问题,设置属性的时候value是字符串,单位也要写。目前先这样,后期会进一步完善这个函数。

 1 function css(obj, attr, value) {
 2     switch (arguments.length) {
 3         case 2://如果只有两个参数要么是读取属性值,要么设置多个属性
 4             if (typeof arguments[1] == "object") {//检测第二个参数是字符串还是json对象
 5                 for (var i in attr) {
 6                     if (i == "opacity") {//opacity属性有兼容性问题
 7                         obj.style["filter"] = "alpha(opacity=" + attr[i] + ")";//ie
 8                         obj.style[i] = attr[i] / 100;//其他
 9                     } else if (i == "float") {
10                         if (obj.style.styleFloat) {
11                             return obj.style.styleFloat; //ie
12                         } else if (obj.style.cssFloat) {
13                             return obj.style.cssFloat; //其他
14                         }
15                     } else {
16                         obj.style[i] = attr[i];
17                     }
18                 }
19             } else {
20                 return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj, null)[attr]
21             }
22             break;
23         case 3://有三个参数就是设置单个属性值
24             if (i == "opacity") {
25                         obj.style["filter"] = "alpha(opacity=" + value + ")";
26                          obj.style[attr] = value / 100;
27                     } else if (i == "float") {
28                         if (obj.style.styleFloat) {
29                             return obj.style.styleFloat=value; //ie
30                         } else if (obj.style.cssFloat) {
31                             return obj.style.cssFloat=value; //火狐
32                         }
33                     } else {
34                         obj.style[attr] = value;
35                     }
36             break;
37     }
38 };

 

posted @ 2017-06-01 00:49  医学生学前端  阅读(306)  评论(0编辑  收藏  举报