javascript - 循环或重复运行一堆 JQuery 函数

标签 javascript jquery html frontend

我正在自学 JQuery,昨天晚上我偶然发现了一个疑问,从那时起就陷入了困境。 简单:我需要动画循环重复。但它不起作用,你能帮帮我吗?我试过 setInterval,它不起作用。 fiddle 是:https://jsfiddle.net/8v5feL9u/

            $(document).ready(function(){



//window.setInterval(function(){

            $(".img1").css({display:''});
            $(".img1").animate({bottom: '300px', opacity: '1'}, 2000, function(){
                $(".img1").fadeOut(700);
                $(".img1").css({display:'none', bottom: '', opacity:'0'});
                $(".img2").css({display:''});
                $(".img2").animate({top: '300px', opacity: '1'}, 2000, function(){
                    $(".img2").fadeOut(700);
                    $(".img2").css({display:'none', top: '', opacity:'0'});
                    $(".img3").css({display:''});
                    $(".img3").animate({bottom: '300px', opacity: '1'}, 2000, function(){
                        $(".img3").fadeOut(700);
                        $(".img3").css({display:'none', bottom: '', opacity:'0'})
                        $(".img4").css({display:''});
                        $(".img4").animate({top: '300px', opacity: '1'}, 2000, function(){
                            $(".img4").fadeOut(700);
                            $(".img4").css({display:'none', top: '', opacity:'0'});

                        });
                    });
                });
            });



//});



        });

非常感谢。

最佳答案

您可以将动画包装在一个函数中,然后在动画最嵌套部分的最后一个“动画完成”回调中递归调用该函数。

function doAnimation() {
  $('.animate')
  .hide()
  .fadeIn(1000, function() {
    $(this).fadeOut(1000, function() {
      // recursively call our function in the inner-most animation callback
      doAnimation();
    });
  })
}

// start out initial loop
doAnimation();
.animate {
  padding: 30px;

  background: cornflowerblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="animate">animate me</div>

关于javascript - 循环或重复运行一堆 JQuery 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44349779/

相关文章:

javascript - 如何在 jQuery 中向 `change` 事件添加属性

javascript 函数说它不存在,当它存在时

javascript - 需要一种方法根据 a 标签的 href 将类添加到特定 div

javascript - 我如何让我的结果连续显示?

javascript - 使用正则表达式解析查询参数

javascript - "require"未定义错误 - javascript

javascript - Bootstrap 的 javascript 在本地工作,但在部署到服务器时不工作

javascript - 在 JavaScript 中格式化字符长度/限制

html - 我该如何解决?卡出DIV

html - 如何格式化 Bootstrap 表以将所有内容左对齐并仅使用必要的空间?