在触发动画之前等待图像加载并调整大小?

时间:2011-02-10 14:54:04

标签: javascript jquery

$("#body-background").ezBgResize();
$("#nav").animate({
        left: "-725px"
    }, 800, "easeOutCirc" );
    $("#page .home").animate({
            right: "0px"
    }, 800, "easeOutCirc" );

这基本上是我的代码。

第一行使用jQuery Easy Background Resize :(参考:http://johnpatrickgiven.com/jquery/background-resize/

在HTML中,你输入如下内容:

<!-- This gets positioned absolutely so place it anywhere. -->
<div id="body-background"><img src="image/bg.jpg" alt="Bg"></div>

我遇到的问题是图像第一次加载需要很长时间,动画不会触发......并跳到最后。无论如何,我可以延迟动画直到调整大小完成后?

提前致谢。

修改:我正在处理的网站:http://jsc.yondershorecreative.com/

1 个答案:

答案 0 :(得分:3)

我能做的最好的事情是模拟图像预加载器并等待它的加载事件:

// grab the background image object
var img = $('#body-background img');

// next, create a new hidden image in the background and bind to the load event
var nImg = $('<img>').bind('load',function(){
  // this is where your "After load" code would go
});

// next, give the image the same URL of the image for the background
// this will force the event to load up and call the load event
nImg.attr('src',img.attr('src'));

适用于jsFiddle(只需更改图像网址中?之后的数字即可模拟清空缓存)。如果有帮助,请告诉我。


更新(下面给出评论)

<script type="text/javascript">
  $('#body-background').azBgResize();

  var homepageAnimation = function(){
    $("#nav").animate({
      left: "-725px"
    }, 800, "easeOutCirc" );
    $("#page .home").animate({
      right: "0px"
    }, 800, "easeOutCirc" );
  }
  $(window).load(function(){
    setTimeout(homepageAnimation,1000);
  });
</script>
相关问题