Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
520 views
in Technique[技术] by (71.8m points)

javascript - Wait until image loads before performing function

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.

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

Here's my code:

 $(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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do it like this:

$('img#image').attr("src", src).one('load',function() {
  $(this).fadeIn(700);
}).each(function() {
  if (this.complete) $(this).trigger('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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...