为什么javascript this.style 返回一个空字符串?

为什么this.style[property]得到一个空字符串? 我的代码是:

    Demo  #test{ height:100px; } .tclass{ width:100px; }   function $(ID){ var element=document.getElementById(ID||'nodId'); if(element){ element.css=css; } return element; } function css(prop,value){ if(value==null){ return this.style[prop]; } if(prop){ this.style[prop]=value; } return true; } window.onload=function(){ var element=$("test"); alert(element.css("height")+","+element.css("width")+","+element.css("background")); //alert ,,#ccc };    
Test

这段代码警报,,#ccc ,但我想得到100px,100px,#ccc ,我有什么问题? 谁能帮我?

更新

我改变了cssfunction,现在它可以正常工作:

  function css(prop,value){ if(value==null){ var b = (window.navigator.userAgent).toLowerCase(); var s; if(/msie|opera/.test(b)){ s = this.currentStyle }else if(/gecko/.test(b)){ s = document.defaultView.getComputedStyle(this,null); } if(s[prop]!=undefined){ return s[prop]; } return this.style[prop]; } if(prop){ this.style[prop]=value; } return true; } 

.style属性用于获取直接放在元素上的样式。 它不会从样式表中计算样式。

请参阅getComputedStyle()

元素没有指定CSS高度或宽度。

请注意,您尝试获取“请求”尺寸,而不是实际尺寸。 因此输出是正确的。

如果要获得有效大小,请使用jQuery width()height()方法。 见http://api.jquery.com/width/