element.style 属性让您只知道在该元素中定义为 inline 的 CSS 属性(以编程方式,或在元素的 style 属性中定义),您应该获得 计算样式。
跨浏览器的方式没那么容易做到,IE有自己的方式,通过element.currentStyle属性,以及DOM Level 2的标准方式,其他浏览器实现的是通过document.defaultView.getComputedStyle 方法。
这两种方式是有区别的,比如IE的element.currentStyle属性期望你访问的CCS属性名是由camelCase中的两个或多个单词组成的(例如maxHeight,fontSize 、backgroundColor 等),标准方式需要用破折号分隔单词的属性(例如 max-height、font-size、background-color 等)。
此外,IE element.currentStyle 将返回所有指定单位的尺寸(例如 12pt、50%、5em),标准方式将始终以像素为单位计算实际尺寸。
我前段时间做了一个跨浏览器的函数,可以让你以跨浏览器的方式获取计算出来的样式:
function getStyle(el, styleProp) {
var value, defaultView = (el.ownerDocument || document).defaultView;
// W3C standard way:
if (defaultView && defaultView.getComputedStyle) {
// sanitize property name to css notation
// (hypen separated words eg. font-Size)
styleProp = styleProp.replace(/([A-Z])/g, "-$1").toLowerCase();
return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
} else if (el.currentStyle) { // IE
// sanitize property name to camelCase
styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) {
return letter.toUpperCase();
});
value = el.currentStyle[styleProp];
// convert other units to pixels on IE
if (/^\d+(em|pt|%|ex)?$/i.test(value)) {
return (function(value) {
var oldLeft = el.style.left, oldRsLeft = el.runtimeStyle.left;
el.runtimeStyle.left = el.currentStyle.left;
el.style.left = value || 0;
value = el.style.pixelLeft + "px";
el.style.left = oldLeft;
el.runtimeStyle.left = oldRsLeft;
return value;
})(value);
}
return value;
}
}
上述函数在某些情况下并不完美,例如对于颜色,标准方法将以 rgb(...) 表示法返回颜色,在 IE 上它们将按原样返回颜色已定义。
我目前正在撰写该主题的一篇文章,您可以关注我对这个功能所做的更改here。