Skip to content

Instantly share code, notes, and snippets.

@hacke2
Created Aug 26, 2014
Embed
What would you like to do?
兼容浏览器的获取指定元素(elem)的样式属性(name)的方法
function getStyle(elem, name){
//如果属性存在于style[]中,直接取
if(elem.style[name]){
return elem.style[name];
}
//否则 尝试IE的方法
else if(elem.currentStyle){
return elem.currentStyle[name];
}
//尝试W3C的方式
else if(document.defaultView && document.defaultView.getComputedStyle){
//W3C中为textAlign样式,转为text-align
name = name.replace(/([A-Z])/g, "-$1");
name = name.toLowerCase();
var s = document.defaultView.getComputedStyle(elem, "");
return s && s.getPropertyValue(name);
} else {
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment