开发者

How to get the width of a div's inner content using jQuery?

I have a div with a bunch of images inside floated left. I want to get the collective width of all the images. I know I can just grab the width of the div since it expands to fit it's contents but how can I do it the other way, by calculating the inner content's width?

EDIT

Sorry here's the markup:

   <div id="gallery">

        <ul>
           <li><img src="images/a.png" /></li>
           <li>&开发者_Python百科lt;img src="images/b.png" /></li>
           <li><img src="images/c.png" /></li>
        </ul>

    </div>

I need to get the width of all the lis combined.


Try this

var totalWidth = 0;
$('#gallery li').each(function(){
    totalWidth  += $(this).outerWidth(true);
});

totalWidth will give you the combined width of all the li's inside the div#gallery


I'm not so sure about this because I haven't done many tests on it. There are two attributes, scrollWidth and scrollHeight which return "the width/height in pixels of the content of an element or the width/height of the element itself, whichever is greater".

This is vanilla JS but you can use it with jQuery too like this:

var totalWidth = $('#gallery').get(0).scrollWidth;

It worked for me. But I haven't tested much.


There is the innerWidth() function. We will need to see your HTML to advise further.


You can try something like this:

    var sumWidth = 0;
    $('selector').each(function(){
        var sumWidth += $(this).width();
    });
    alert('the width sum is: '+sumWidth);

Hope it helps!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜