【问题标题】:Loading image in random position on page load在页面加载时在随机位置加载图像
【发布时间】:2016-05-15 15:47:24
【问题描述】:

我正在为我的设计工作在一个作品集网站上工作,但遇到了一个小问题。

我正在尝试将图像加载到随机位置,然后使用 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

【问题讨论】:

  • 第二行应该缩进,并且不与$ ->对齐,虽然我怀疑这是一个复制粘贴错误。它在你的代码中吗?
  • 是的复制粘贴错误,它在我的代码中缩进了
  • 好吧,我可以告诉你什么不起作用:你正在绑定的e.onload() 事件不会针对每张图片触发。而且由于它们都位于加载时的左上角,因此有时有些会留在那里。这可能是全局就绪 $->onload 本身之间的竞争条件。
  • 我同意@ArcaneCraeda,图像可以被缓存,所以它们在 JS 执行之前被加载,这意味着onload 不会被触发。 @Nate:你说有时它有效。它是否在第一次尝试时起作用,然后停止?
  • @LcLk 正确,它在第一次尝试时有效,但在之后无效。您认为缓存图像的最佳方法是什么?

标签: javascript jquery html css coffeescript


【解决方案1】:

所以问题是图像被浏览器缓存了。好吧,这确实是一件好事,但这意味着不会为所有图像触发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

【讨论】:

    猜你喜欢
    • 2021-04-25
    • 2017-02-20
    • 1970-01-01
    • 1970-01-01
    • 2016-05-01
    • 1970-01-01
    相关资源
    最近更新 更多