等到执行功能之前图像加载 [英] Wait until image loads before performing function

查看:136
本文介绍了等到执行功能之前图像加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个简单的投资组合页面。我有一个拇指和图像列表。当您单击拇指时,图像将会改变。

I'm trying to create a simple portfolio page. I have a list of thumbs and an image. When you click on a thumb, the image will change.

单击缩略图时,我希望图像淡出,等到图像加载然后重新开始。我现在遇到的问题是,有些图像非常大,所以它会淡出,然后立即消失,有时图像仍在加载。

When a thumbnail is clicked, I'd like to have the image fade out, wait until the image is loaded, then fade back in. The problem I have right now is that some of the images are pretty big, so it fades out, then fades back in immediately, sometimes while the image is still loading.

我想避免使用setTimeout,因为有时图像的加载速度会比我设置的时间更快或更慢。

I'd like to avoid using setTimeout, since sometimes an image will load faster or slower than the time I set.

这是我的代码:

 $(function() {
     $('img#image').attr("src", $('ul#thumbs li:first img').attr("src"));

     $('ul#thumbs li img').click(function() {
         $('img#image').fadeOut(700);

         var src = $(this).attr("src");
         $('img#image').attr("src", src);

         $('img#image').fadeIn(700);
     });
 });

<img id="image" src="" alt="" />
<ul id="thumbs">
    <li><img src="/images/thumb1.png" /></li>
    <li><img src="/images/thumb2.png" /></li>
    <li><img src="/images/thumb3.png" /></li>
</ul>


推荐答案

你可以这样做:

$('img#image').attr("src", src).one('load',function() {
  $(this).fadeIn(700);
}).each(function() {
  if (this.complete) $(this).trigger('load');
});

如果图像被缓存,在某些浏览器中 .load()不会触发,所以我们需要通过检查 .complete 来检查并处理这种情况并手动激活加载。 .one()确保当时是否缓存或加载, load 处理程序仅触发一次。

If an image is cached, in some browsers .load() won't fire, so we need to check for and handle this case by checking .complete and firing load manually. .one() ensures whether it's cached or loaded at that time, that the load handler only fires once.

这篇关于等到执行功能之前图像加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆