JavaScript 获取计算后的样式

w3c标准浏览器的获取方法

 1 var oDiv = document.getElementById('div');
 2 //获取计算后的font-size
 3 var sFs = getComputedStyle(oDiv,null).getPropertyValue('font-size');//推荐使用
 4 //或者
 5 var sFs= getComputedStyle(oDiv,null).fontSize; //不推荐使用
 6 
 7 console.log(sFs);
 8 
 9 //注1: 由于获取不同浏览器里计算后的css属性名称的不同(比如获取float),在有些浏览器是.cssFloat,有些则是.styleFloat,为了避免浏览器判断,使用.getPropertyValue('float')就可以避免这个问题。
10 //注2: .getPropertyValue()方法里的值不支持驼峰写法,比如fontSize只能写成getPropertyValue('font-size')这种形式
11 }

 

IE9以下浏览器的获取方法:

1 var oDiv = document.getElementById('div');
2 //获取计算后的font-size
3 var sFs= oDiv.currentStyle.getAttribute('font-size'); //推荐使用
4 //或者
5 var sFs= oDiv.currentStyle.fontSize; //不推荐使用
6 
7 console.log(sFs)

封装获取计算后样式的方法

 1 function getStyle(node,attr){
 2     if(typeof getComputedStyle != 'undefined'){
 3         var value = getComputedStyle(node,null).getPropertyValue(attr);
 4         return attr == 'opacity' ? value * 100 : value; //兼容不透明度,如果是不透明度,则返回整数方便计算
 5     }else if(typeof node.currentStyle != 'undefined'){
 6         if(attr == 'opacity'){ //兼容不透明度
 7             return Number(node.currentStyle.getAttribute('filter').match(/(?:opacity[=:])(\d+)/)[1]);
 8         }else{
 9             return node.currentStyle.getAttribute(attr);
10         }
11     }
12 }

 

posted @ 2018-07-14 10:53  shengzs  阅读(547)  评论(0编辑  收藏  举报