如何更改功能呼叫顺序



我有一个图像列表( <img>),我像下面的代码一样迭代

中的代码
$('.img').each(function(key,value){
  (function(){
    $(value).fadeOut('slow');
    $(value).attr('src','images/new.png');
    $(value).fadeIn('slow');
  })()
})

问题是 - 如何更改属性,然后调用fadeOut/fadeIn函数。在这种情况下 - 首先,属性变化,而两种效果都可以。

使用fadeOut回调; fadeOut 启动 vadeout过程,但它继续并完成异步(稍后)。另外,不需要该内部功能:

$('.img').each(function(key,value){
    var $value = $(value);
    $value.fadeOut('slow', function() {      // Note we're using
        $value.attr('src','images/new.png'); // the callback
        $value.fadeIn('slow');               // to run this
    });
});

或:

$('.img').each(function(key,value){
    $(value).fadeOut('slow', function() {
        $(this).attr('src','images/new.png')
               .fadeIn('slow');
    });
});

如果该图像(images/new.png)可能不在缓存中,则最好将其置。否则,fadeIn可能在加载图像之前开始。等待图像上的load事件可能会出现问题,尤其是在您正在更改src的现有img元素上。如果您想等待load,我可能会完全替换img,例如:

$('.img').each(function(key,value){
    $(value).fadeOut('slow', function() {
        $("<img class=img>")
            .on("load", function() { // Note hooking load BEFORE setting src
                $(this).fadeIn('slow');
            })
            .attr("src", "images/new.png")
            .hide()
            .replaceAll(this);
    });
});

...但是,

真的很简单。

实时示例:

$('.img').each(function(key, value) {
  $(value).fadeOut('slow', function() {
    $("<img class=img>")
      .on("load", function() { // Note hooking load BEFORE setting src
        $(this).fadeIn('slow');
      })
      .attr("src", "https://www.gravatar.com/avatar/1c9adcda917a5646e8ebe93738d23a3f?s=328&d=identicon&r=PG&f=1")
      .hide()
      .replaceAll(this);
  });
});
<img class="img" src="https://www.gravatar.com/avatar/ca3e484c121268e4c8302616b2395eb9?s=328&d=identicon&r=PG">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

这是因为动画是执行异步的。

正如您需要从fadeOut使用回调参数的评论中提到的某人:

$('.img').each(function(key, value) {
    $(value).fadeOut('slow', function() {
        // fadeOut animation completed
        $(value).attr('src','images/new.png')
        $(value).fadeIn('slow')
    })
})

您可以使用JQuery使用JavaScript .promise(),您可以用作$.when()

$('.img').each(function(key, value) {
    $.when($(value).fadeOut()).done(function() {
        $(value).attr('src', 'https://www.gravatar.com/avatar/1c9adcda917a5646e8ebe93738d23a3f?s=328&d=identicon&r=PG&f=1').fadeIn();
   })
});

$('.img').each(function(key, value) {
  $.when($(value).fadeOut()).done(function() {
    $(value).attr('src', 'https://www.gravatar.com/avatar/1c9adcda917a5646e8ebe93738d23a3f?s=328&d=identicon&r=PG&f=1').fadeIn();
  })
});
<img class="img" src="https://www.gravatar.com/avatar/62c8139675bef978e1d92c816f052262?s=328&d=identicon&r=PG&f=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

最新更新