如何使用JQuery添加div中所有图像的宽度 [英] How to add the widths of all the images in a div with JQuery

查看:156
本文介绍了如何使用JQuery添加div中所有图像的宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找一种方法来将div的宽度更改为该div内所有宽度的总和。

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.

换句话说,我want#page-content的宽度等于其中所有图片的宽度。这是因为我希望page-content 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.

我的代码如下:

    <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>

我试用的jQuery是:

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.

非常感谢任何帮助

西多夫

推荐答案

我建议为图片添加一个类,因为你有链接,即< img class =shutterimg并尝试在$(window).load函数中确保它们已加载:

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);

这篇关于如何使用JQuery添加div中所有图像的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆