用一个函数
function fetchComputedStyle(obj, property)传入两个参数,参数1-对象,参数2-属性名;
判断该运行环境是否可以运行getComputedStyle来获取属性值,以输出最佳结果:
if(window.getComputedStyle){
//由于该函数属性值为驼峰型,所以若property是“-”连接形式的属性名则应将“-”和它后面第一个字符转化为该字符的大写形式
//字符替换,正则表达式
property = property.replace(/([A-Z])/g, function(match,$1){
return "-" + $1.toLowerCase();
})
return getComputedStyle(obj)[property]; // getComputedStyle(对象名)
}else{
//和上面差不多,将“-”+连接的第一个小写字符转换成大写
proerty = property.replace(/\-([a-z])/,function(match, $1){
return $1.toUpperCase();
})
return obj.currentStyle[property]; // 对象.currentStyle
}
这样就可以直接调用这个函数,无论什么浏览器,都不会出现兼容问题啦