【问题标题】:jQuery - .width() returning 0 on imgs with max-heightjQuery - .width() 在最大高度的 imgs 上返回 0
【发布时间】:2013-05-06 07:08:38
【问题描述】:

所以我有一个水平滚动的 div,我需要根据其中动态生成的图像列表找出该 div 需要多宽。

我想使用 jQuery 来查找所有图像的宽度,并将 div 的宽度设置为该整数。

这是我的 jQuery 不起作用:

<script>

    function findWidth() {

        var totalwidth = 0;
        $('img.you').each(function() {
            totalwidth += $(this).width();
            console.log($(this).css("width"));
        });
        $('#scrollbox').css("width", totalwidth);

    }

    $(document).ready(function() {
        findWidth();
    });

</script>

应用于我的每张图片的 CSS:

.you {
    max-height: 215px;
    position: relative;
    float:left;
    border: 7px solid #f5f5f5;
    margin-left: 15px;
    box-shadow: 0 2px 7px rgb(70, 70, 70);
}

我试过 .width() 和 .css("width")... 没有。

我已经尝试过 $(document).ready() 和 .load()... 什么都没有。

这是我的 PHP,它显示了我在其他地方填充的数组中的所有图像:

<?php

    //$myImages is an array of links.
    $index = 0;
    foreach($myImages as $key=>$value) {
        // do stuff
        $index++;

        echo <<<EOF
        <img class="you" src="$value" alt="">
EOF;

    }
?>

问题:

问题是无论它是什么图像都保持记录 0。

【问题讨论】:

    标签: php jquery width dynamically-generated


    【解决方案1】:

    您没有在 CSS 中设置 width,因此使用 css('width') 可能会得到 auto,因为这是宽度的默认 CSS 值,而 width() 会得到 0,因为图像不是已加载但没有宽度?

    要获得实际的图像,您必须等到它们被加载,但这样的事情应该可以工作:

    function findWidth() {
        var totalwidth = 0;
        $('img.you').each(function() {
            totalwidth += $(this).width();
        });
        $('#scrollbox').css("width", totalwidth);
    }
    
    $(window).on('load', function() {
        findWidth();
    });
    

    【讨论】:

    • @RickBross - jQuery 太老了,现在是 2.0 版!
    猜你喜欢
    • 1970-01-01
    • 2010-12-05
    • 1970-01-01
    • 1970-01-01
    • 2015-03-20
    • 2012-10-30
    • 1970-01-01
    • 2019-05-02
    • 1970-01-01
    相关资源
    最近更新 更多