2012-02-25 77 views
5

爲什麼this.style[property]得到一個空字符串?我的代碼是:爲什麼JavaScript this.style [property]返回一個空字符串?

<!DOCTYPE html> 
<html> 
<head> 
    <title>Demo</title> 
    <style type="text/css"> 
     #test{ 
      height:100px; 
     } 
     .tclass{ 
      width:100px; 
     } 
    </style> 
    <script type="text/javascript"> 
     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 
     }; 
    </script> 
</head> 
<body> 
    <div id="test" style="background:#CCC;" class="tclass">Test</div> 
</body> 
</html> 

這段代碼警報,,#ccc,但我希望得到100px,100px,#ccc,這有什麼錯嗎?誰能幫我?

更新

我改變了CSS功能,現在它可以很好地工作:

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; 
    } 
+0

那麼,DOM元素沒有'style'屬性。所以你不能得到他們的'樣式'屬性。 – 2012-02-25 14:24:25

+0

'elem.style'正在訪問元素具有的樣式*屬性*。 – pimvdb 2012-02-25 14:26:00

回答

22

.style屬性用於獲取直接放置在元素上的樣式。它不會從樣式表中計算樣式。

請參閱getComputedStyle()

+0

:我更新我的代碼(css函數),現在它可以很好地工作 – artwl 2012-02-25 14:50:14

1

的元素沒有指定一個CSS高度或寬度。

請注意,您正在嘗試獲取「請求」尺寸,而不是實際尺寸。因此輸出是正確的。

如果您想獲得有效大小,請使用jQuery width()height()方法。請參閱http://api.jquery.com/width/

相關問題