2013-05-11 19 views
0

所以我有一個水平滾動div,我需要找出div的寬度需要基於動態生成的圖像列表的內容。jQuery - .width()在最大高度爲imgs時返回0

我想使用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 (「寬度」)...沒有。

我試過$(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不管是什麼它的形象。

回答

1

你在CSS沒有width設定,因此使用css('width')可能讓你auto,因爲這是對寬度的默認CSS值,width()讓你0,作爲圖像are'nt尚未加載,沒有寬度是多少?

要獲得實際與圖片,你將不得不等待,直到他們被加載,但這樣的事情應該工作:

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

$(window).on('load', function() { 
    findWidth(); 
}); 
+0

遺漏的類型錯誤:對象#有「上」沒有方法。 .. – 2013-05-11 22:54:50

+0

@RickBross - 太舊的jQuery,它現在在2.0版本! – adeneo 2013-05-11 22:55:43

+0

'.load()'照顧它。不用擔心,謝謝! – 2013-05-12 17:48:10

相關問題