2010-12-20 33 views
3

1.4.4隱藏元素的返回大小,但是另一個隱藏元素中的元素呢? 有沒有更好的解決方案,然後getWidth?如何獲取隱藏父元素的大小?

<script type="text/javascript"> 
     function getWidth(element){ 
      var parent = element.parent(); 
      $('body').append(element); 
      var width = element.width(); 
      parent.append(element); 
      return width; 
     } 

     $(function(){ 
      var width = $("#foo").width(); 
      console.log(width); //0 
      width = getWidth($("#foo")); 
      console.log(width); //ok 
     }); 
    </script> 
    <div style='display:none'> 
     <div style='display:none' id='foo'>bar</div> 
    </div> 
+2

請參閱http://stackoverflow.com/questions/1841124/find-the-potential-width-of-a-hidden-element – Flo 2010-12-20 09:14:47

回答

1

當元素被隱藏時,它們的寬度可能因樣式而異。當一個隱藏的元素在另一個隱藏的元素內時,結果可能會再次變化。然而,jQuery代碼非常簡單:

$('#foo').parent().width() 

這會搶富的母公司格,然後抓住它的寬度,但我不能保證它會得到元素的取消隱藏自然寬。希望有所幫助!