2010-01-20 116 views
0

是否有可能獲得div的所有圖像的寬度,然後用jquery將#content css設置爲該值?我使用一個項目的水平佈局,並需要不時添加圖像。用jquery獲取圖像的div寬度圖像寬度

<div id="content"> 
    <div class="entry"> 
    image 
    image 
    </div> 
<div class="entry"> 
    image 
    image 
</div> 
</div> 

回答

2

也許你可以試試

var width = 0; 
$.each(jQuery('img'), function(i, img) { 
    width += $(img).width(); 
}); 
$('#content').width(width); 
+0

非常感謝!有用! – jelm 2010-01-30 13:28:29

0

想到的是閱讀的內容div的內容,發現每IMG標籤,並獲取其相關的寬度(同時保持總運行),然後指定內容div的寬度只有這樣,總數。

1

大廈斷@ Bob的答案。我沒有嘗試過,但在我看來,.width()函數不會考慮填充和邊距。如果這樣做,那麼你只需要.width(),否則像下面的東西。

width = 0; 
$.each(jQuery('.entry'), function(i, e) { 
    width += $(e).width() 
      + $(e).css("margin-left") + $(e).css("margin-right") 
      + $(e).css("padding-left") + $(e).css("padding-left"); 
}); 
$('#content').width(width);