这个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),标准方法总是计算实际大小(以像素为单位)。
不久前,我创建了一个跨浏览器函数,允许您以跨浏览器的方式获取计算样式:functiongetStyle(el,styleProp){
varvalue,defaultView=(el.ownerDocument||document).defaultView;
//W3Cstandardway:
if(defaultView&&defaultView.getComputedStyle){
//sanitizepropertynametocssnotation
//(hypenseparatedwordseg.font-Size)
styleProp=styleProp.replace(/([A-Z])/g,"-$1").toLowerCase();
returndefaultView.getComputedStyle(el,null).getPropertyValue(styleProp);
}elseif(el.currentStyle){//IE
//sanitizepropertynametocamelCase
styleProp=styleProp.replace(/\-(\w)/g,function(str,letter){
returnletter.toUpperCase();
});
value=el.currentStyle[styleProp];
//convertotherunitstopixelsonIE
if(/^\d+(em|pt|%|ex)?$/i.test(value)){
return(function(value){
varoldLeft=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;
returnvalue;
})(value);
}
returnvalue;
}}
上面的函数在某些情况下并不完美,例如对于颜色,标准方法将在RGB(.)表示法,在IE上,它们将按定义返回它们。
我目前正在写一篇关于这个主题的文章,您可以跟踪我对这个函数所做的更改。这里.