How to add the widths of all the images in a div with JQuery

我与影子孤独终老i 提交于 2019-12-08 04:11:16

问题


I was looking for a way to change the width of a div to the sum of all the widths of the images within that div.

In other words, I wanted #page-content to have a width that is equal to the width of all the images inside it. This is because i would like the page-content div to be wider than the browser window, so that the user can scroll from left to right.

the code I had was as follows:

    <div id="page-content">
    <div id="gallery">
        <div>
            <a href="#" class="shutterset">
                <img src="images/pic1.jpg"/>
            </a>
            <a href="#" class="shutterset" >
                <img src="images/pic2.jpg" />
            </a>
            <a href="#" class="shutterset" >
                <img src="images/pic3.jpg" />
            </a>
            <a href="#" class="shutterset" >
                <img src="images/pic4.jpg" />
            </a>
            <a href="#" class="shutterset" >
                <img src="images/pic5.jpg" />
            </a>
            <a href="#" class="shutterset" >
                <img src="images/pic6.jpg" />
            </a>
            <a href="#" class="shutterset" >
                <img src="images/pic7.jpg" />
            </a>
            <a href="#" class="shutterset" >
                <img src="images/pic8.jpg" />
            </a>
        </div>
        <div class="clear"> </div>
        <p>hi</p>
    </div>
</div>

And the jQuery I tried out was:

        $(document).ready(function() {
        $("p").html($("#gallery img:first").width());
    });

I'd done this to test to see if the width was being calculated, but it doesnt seems to be. The result is always 0, as opposed to the width of the image.

Would appreciate any help

Seedorf


回答1:


I suggest adding a class to the images as you have the links, i.e. <img class="shutterimg" and trying this in a $(window).load function to be sure they have loaded:

var totalwidth = 0;
$('img.shutterimg').each(function() {
    totalwidth += $(this).width();
});
$('#gallery').width(totalwidth);



回答2:


Image widths are not calculated until the image is downloaded, unless the width attribute is specified. Your handler executes on $(document).ready() -- this is when the whole DOM has loaded but will almost certainly be before the images have loaded.

Wait for the $(window).load() event instead: this is triggered when all the content (images, stylesheets and scripts) has loaded.

$(window).load(function() {
    $("p").html($("#gallery img:first").width());
});


来源:https://stackoverflow.com/questions/6257372/how-to-add-the-widths-of-all-the-images-in-a-div-with-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!