代码改变世界

javascript 取非内嵌CSS的值的方法【收藏】

2011-08-30 16:59  古小古  阅读(152)  评论(0编辑  收藏  举报
 1 //o : dom对象
2 //k : 样式名称
3 function getStyle(o, k) { 
4   //处理样式名称:background-color→backgroundColor
5   var _k = k.replace(/-[a-z]/g, function(a) {return a.substr(1,1).toUpperCase()});
6   //如是内嵌样式直接获取
7   var v = o.style[_k];
8 if(!v) {
9     //FF 获取非内嵌样式信息 document.defaultView.getComputedStyle
10     if (document.defaultView && document.defaultView.getComputedStyle) {
11 var c = document.defaultView.getComputedStyle(o, null);
12 v = c ? c.getPropertyValue(_k) : null;
13 }
14    //IE 获取非内嵌样式信息 currentStyle
15    else if (o.currentStyle) {
16 v = o.currentStyle[_k];
17 }
18 }
19 return v;
20 }