宝慕林4294392
这个element.style属性只让您知道定义为内联在该元素(以编程方式或在元素的样式属性中定义)中,您应该获得计算样式.用跨浏览器的方式做它并不容易,IE有自己的方式,通过element.currentStyle属性,以及DOM级别2。标准方法,由其他浏览器通过document.defaultView.getComputedStyle方法。这两种方式有不同,例如IEelement.currentStyle中的两个或多个单词组成的ccs属性名称。CamelCase(如:maxHeight, fontSize, backgroundColor等等,标准的方式期望属性用虚线分隔的单词(例如。max-height, font-size, background-color(等)同时,IEelement.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上,它们将按定义返回它们。我目前正在写一篇关于这个主题的文章,您可以跟踪我对这个函数所做的更改。这里.