W3C标准浏览器的获取方法:
var oDiv = document.getElementById('div');
//获取计算后的font-size
var sFs = getComputedStyle(oDiv,null).getPropertyValue('font-size');//推荐使用
//或者
var sFs= getComputedStyle(oDiv,null).fontSize; //不推荐使用
console.log(sFs);
//注1: 由于获取不同浏览器里计算后的css属性名称的不同(比如获取float),在有些浏览器是.cssFloat,有些则是.styleFloat,为了避免浏览器判断,使用.getPropertyValue('float')就可以避免这个问题。
//注2: .getPropertyValue()方法里的值不支持驼峰写法,比如fontSize只能写成getPropertyValue('font-size')这种形式
}
IE9以下浏览器的获取方法:
var oDiv = document.getElementById('div');
//获取计算后的font-size
var sFs= oDiv.currentStyle.getAttribute('font-size'); //推荐使用
//或者
var sFs= oDiv.currentStyle.fontSize; //不推荐使用
console.log(sFs);
封装获取计算后样式的方法
function getStyle(node,attr){
if(typeof getComputedStyle != 'undefined'){
var value = getComputedStyle(node,null).getPropertyValue(attr);
return attr == 'opacity' ? value * 100 : value; //兼容不透明度,如果是不透明度,则返回整数方便计算
}else if(typeof node.currentStyle != 'undefined'){
if(attr == 'opacity'){ //兼容不透明度
return Number(node.currentStyle.getAttribute('filter').match(/(?:opacity[=:])(\d+)/)[1]);
}else{
return node.currentStyle.getAttribute(attr);
}
}
}

本文介绍了一种兼容W3C标准及IE9以下浏览器的计算后样式获取方法,并提供了兼容不同浏览器的JavaScript代码实现。
901

被折叠的 条评论
为什么被折叠?



