Wait until image loads before performing function

前端 未结 3 792
我寻月下人不归
我寻月下人不归 2020-12-21 00:49

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

相关标签:
3条回答
  • 2020-12-21 01:33
     $(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)
                 .load(function() {
                     $(this).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>
    
    0 讨论(0)
  • 2020-12-21 01:36

    You need to queue the animations.

    See this page for more info + possible solutions

    0 讨论(0)
  • 2020-12-21 01:45

    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.

    0 讨论(0)
提交回复
热议问题