开发者

Jquery: add the width of all image elements within a container

I have an idea of how I might do this but I was wondering if anyone had a better thought or could help me out. I have an unordered list with a varying number of images dynamically generated within them. I'd like to add the width of each image and set the containing unordered list width to that value.

F开发者_JS百科or example, if three images were output the html might look like this:

<ul id="thumbnails">
    <li><a href="#"><img src="image_path"></a></li>
    <li><a href="#"><img src="image_path"></a></li>
    <li><a href="#"><img src="image_path"></a></li>
</ul>

If image one was 200px, image two was 100px, and image three was 50px, I'd like to assign the width of the thumbnails ul to 350px.

$('#thumbnails').css('width', '350px');

Each image does have a 2px margin-right applied to the line item though, so I'd like to add this to the image as well. So if 3 images were generated I'd like the total width to be 356px.

Thanks all for any help. I've been looking at jquery's each() and width() functions to accomplish this.


var accum_width = 0;
$('#thumbnails').find('img').each(function() {
   accum_width += $(this).width() + 2;
});
$('#thumbnails').width(accum_width);


Thanks for the code. To get it working with Safari and Chrome I needed to load it with window load not dom ready. Not sure what the downside to this method is but im guessing their is one as dom ready is more common.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜