【问题标题】:How to add the widths of all the images in a div with JQuery如何使用 JQuery 在 div 中添加所有图像的宽度
【发布时间】:2011-09-09 14:03:25
【问题描述】:

我正在寻找一种将 div 的宽度更改为该 div 中所有图像宽度之和的方法。

换句话说,我希望#page-content 的宽度等于其中所有图像的宽度。这是因为我希望页面内容 div 比浏览器窗口更宽,以便用户可以从左向右滚动。

我的代码如下:

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

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

我这样做是为了测试是否正在计算宽度,但似乎没有。结果始终为 0,而不是图像的宽度。

不胜感激

西多夫

【问题讨论】:

    标签: jquery css width


    【解决方案1】:

    我建议在您拥有链接时为图像添加一个类,即&lt;img class="shutterimg" 并在 $(window).load 函数中尝试此操作以确保它们已加载:

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

    【讨论】:

    • 你愿意嫁给我吗!!!? :-) 这行得通!不得不添加一个括号和分号。非常感谢!
    【解决方案2】:

    除非指定了width 属性,否则在下载图像之前不会计算图像宽度。您的处理程序在 $(document).ready() 上执行——这是整个 DOM 已加载的时间,但几乎可以肯定是在图像加载之前。

    请等待$(window).load() 事件:当所有内容(图像、样式表和脚本)已加载时触发。

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

    【讨论】:

    • 是的,这适用于问题的第一部分。设法得到显示的尺寸!!! #upvoted
    猜你喜欢
    • 2021-08-15
    • 1970-01-01
    • 2011-04-15
    • 2016-08-28
    • 2014-10-04
    • 2013-01-01
    • 1970-01-01
    • 2014-02-12
    • 1970-01-01
    相关资源
    最近更新 更多