问题:
获取元素的真实的样式。在DHTML中经常需要操作css属性,但是取值不是很方便。因为直接元素.style.属性的方式取到的是元素的style属性的值,不能得到<style>元素内的值。 

方法:
1基本情况

.1 在HTML种有三种方式定义样式。分别是link外部导入,style元素,元素的style属性
  在DOM2 Styles中提供了一套以上的API
  访问Style属性,必须使用驼峰法的方式

.2   获取真实style的值
  IE下使用currentStyle。ff下使用getComputedStyle。这两种方式可以取到样式定义的三种方式混合后的最终结果。

.3   直接获取和设定整个style的值。
  1使用getAttribute("style")或者.style返回。
   这种情况下。ie6/7返回object。ff在getAttribute时返回style的值,在.style时返回[cssStyleDeclaration]
  2使用style.cssText
   对于style="border:1px solid".这种情况下,ff返回原始值。ie返回border-top,borde-left,border-right,border-bottom


2一些库的具体实现

1:下面看moo中的getStyle实现

getComputedStyle: function(property){
if (this.currentStyle) return this.currentStyle[property.camelCase()];
var defaultView = Element.getDocument(this).defaultView,
computed
= defaultView ? defaultView.getComputedStyle(this, null) : null;
return (computed) ? computed.getPropertyValue((property == floatName) ? 'float' : property.hyphenate()) : null;
},

2:这里是百度tangram的实现和moo相似

baidu.dom.getComputedStyle = function(element, key){
element
= baidu.dom._g(element);
var doc = baidu.dom.getDocument(element),
styles;
if (doc.defaultView && doc.defaultView.getComputedStyle) {
styles
= doc.defaultView.getComputedStyle(element, null);
if (styles) {
return styles[key] || styles.getPropertyValue(key);
}
}
return '';
};

这里的以上getDocument的实现

getDocument: function(){
return this.ownerDocument;
},


关于defaultView的兼容性

3自己的总结

getStyle:function(value){
if(this.currentStyle)return this.currentStyle[value];
return this.ownerDocument.defaultView.getComputedStyle(this, null).getPropertyValue(value)
}


posted on 2011-06-22 15:54  日—月  阅读(316)  评论(0编辑  收藏  举报