2016-02-05 183 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