2016-02-05 147 views
-1

我工作的一個投資組合的網站我的設計工作,我遇到了一個小問題。加載圖像在頁面加載

我試圖加載在隨機位置的圖像,然後使用Dragabilly使圖像拖動。

在時間的圖像都在右上角結束,就好像他們的立場沒有定義。拖動仍然有效。我懷疑這是在執行腳本之前沒有完全加載圖像的問題,但我不確定。

我的網站是活的here

這裏是我使用的是什麼...

$ -> 
$('#menu-button').on 'click', -> 
    $('#menu').toggleClass 'closed' 
    return 

if $(window).width() > 960 
    $img = $ '.work-imgs img' 

    wdoh = $('.work-desc').outerHeight() 
    wl = ($(window).width() - 384)/$img.length 
    wh = $(window).height() - wdoh 

    $.each _.shuffle($img), (i, e) -> 
     e.onload = -> 
      rm = wh - $(e).height() 
      $(e).css 
       'left': i * wl + (Math.random() - .75) * 96 
       'top': wdoh + Math.random() * rm 
      return 
     return 

    $d = $img.draggabilly() 
    $d.on 'pointerDown', -> 
     $d.css 'z-index', 0 
     $(this).css 'z-index', 1 
     return 

return 

Example image

+0

第二行應該縮進,並且不與'$ - >'對齊,儘管我懷疑這是一個複製粘貼錯誤。是否在你的代碼中? – GAntoine

+0

是複製粘貼錯誤,它在我的代碼中縮進 – Nate

+1

嗯,我可以告訴你什麼不起作用:你綁定的'e.onload()'事件不會爲每張圖片觸發。而且,由於他們都在負載的左上角,有些人留在那裏。它可能是全局準備好的'$ - >'和'onload'本身之間的競爭條件。 – GAntoine

回答

0

所以問題是這些圖像是由瀏覽器緩存。那麼這真是一件好事,但這意味着所有圖像都不會觸發onload事件。相反,當您分配回叫時,您必須檢查圖像是否已經加載。

要檢查圖像是否已在JS執行之前加載,可以使用complete屬性(mdn)。

$.each _.shuffle($img), (i, e) -> 
     callback = -> 
     rm = wh - $(e).height() 
     $(e).css 
      'left': i * wl + (Math.random() - .75) * 96 
      'top': wdoh + Math.random() * rm 

     # if the image isn't cached, the onload will fire 
     e.onload = callback 
     # if the image is cached in the browser, and therefore already 
     # loaded, you can run your callback immediately 
     callback() if e.completed