Skip to content

Instantly share code, notes, and snippets.

@hacke2
Created August 26, 2014 07:28
Show Gist options
  • Save hacke2/d6a6ed049919414ec256 to your computer and use it in GitHub Desktop.
Save hacke2/d6a6ed049919414ec256 to your computer and use it in GitHub Desktop.
兼容浏览器的获取指定元素(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