在setInterval内停止jQuery动画功能,并将css不透明度设置为0

Stop jQuery animate function within setInterval and assign css opacity to 0

本文关键字:css 并将 不透明度 设置 功能 setInterval 动画 jQuery      更新时间:2023-09-26

在jQuery的animate函数完成将不透明度值从0更改为1后,我有一个设置不透明度为0的问题。任何帮助都会很感激。

var i = -1;
var interval = setInterval($.proxy(function () {
    i++;
    if (i >= this.options.slices) {
        clearInterval(interval);
        this.$element.children("[class='" + this.options.clonesClass + "']" ).css("opacity", 0);
    } else {
        this.$element.children("[data-index='" + i + "']").stop().animate({ opacity: 1 }, 1000);
    }
}, this), 50)

看看动画文档。如果你想要实现的是在动画完成后执行一个动作,那么将执行该动作的函数作为最后一个参数传递给animate

所以基本上这个

this.$element.children("[data-index='" + i + "']").stop().animate({ opacity: 1 }, 1000)

应该变成类似

的东西
this.$element.children("[data-index='" + i + "']").stop().animate({ opacity: 1 }, 1000, function(){
    $element.css({opacity:0});
})

编辑:

jQuery并不真正需要处理间隔。假设要动画的元素是$element,只需执行
$element.stop().animate({ opacity: 1 }, 1000, function(){
    $element.css({opacity:0});
})

编辑:

要实现你在注释中描述的,你需要在一个序列中链接动画调用。我建议使用这样的递归结构(伪代码):

function myAnimate(elementsArray, num) {
  if (num < elementsArray.size) {
    $(elementsArray[num]).animate({ opacity: 1 }, 1000, function(){
      myAnimate(elementsArray, num + 1);
    })
  } else {
    for each el in elementsArray {
      $(el).css({opacity:0});
    }
    // do other things, like prepare for next iteration
    // then maybe call myAnimate(elementsArray, 0)
    // to start all over again
  }
}

然后这样命名

myAnimate($('div.toBeAnimated'), 0)

这是我实现我想要的结果的唯一方法。

var t = this;
t.$element.children( "[class='" + t.options.clonesClass + "']" ).each( $.proxy( function () {

    setTimeout( $.proxy( function () {
        i++;
        if ( i < t.options.slices ) {
            $( this ).animate( { opacity: 1 }, 1000 )
        } else {
            $( this ).animate( { opacity: 1 }, 1000, function () {
                t.$element.children( "[class='" + t.options.clonesClass + "']" ).css( "opacity", 0 );
            } );
        }

    }, this ), timeBuffer );
    timeBuffer += 50;

} ), this );