element.style
属性只让您知道在该元素中定义为inline的CSS属性(以编程方式,或在元素的style属性中定义),您应该得到computed style.
用跨浏览器的方式实现这一点并不容易,IE有自己的方式,通过element.currentStyle
属性,其他浏览器实现的DOM Level 2 standard方式是通过document.defaultView.getComputedStyle
方法.
这两种方法有所不同,例如,IE element.currentStyle
属性期望您访问由camelCase中的两个或多个单词组成的CCS属性名称(例如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;
}
}
上面的函数对于某些情况并不完美,例如对于 colored颜色 ,标准方法将返回rgb(...)表示法的 colored颜色 ,在IE上,它们将返回定义的 colored颜色 .
我正在写一篇关于这个主题的文章,你可以跟随我对这个函数所做的修改.