javascript - 以暂停方式在循环中单独设置动画 Div

标签 javascript jquery css animation

我正在尝试制作一个循环动画,每个框都单独显示。为了让您更好地了解动画应该如何工作:

没有显示 > 红框动画进入,显示 5 秒 > 红框动画结束 > 暂停 10 秒 > 绿框动画进入,显示 5 秒 > 等等

我设法用一种复杂的 JQuery 函数来完成这个,所以我希望在这里发帖,看看是否有更简单的方法来做到这一点。

Link to JS Fiddle (The JS in this link is not working, but you can see what I started with)

HTML

<div id="container">
    <div id="red" class="box"></div>
    <div id="green" class="box"></div>
    <div id="blue" class="box"></div>
</div>

CSS

.box {
    width: 200px;
    height: 200px;
    animation: box .6s ease-in;
}

#red {
    background: red;
}

#green {
    background: green;
}

#blue {
    background: blue;
}

@keyframes box {                                                            
  0% {opacity: 0;transform: translateY(-40px);}
  100%{opacity: 1;transform: translateY(0px);}
}

最佳答案

您可以使用递归方法处理它,使用以下逻辑:

var $boxes = $('.box');

(function animateBox(i) {
    $boxes.eq(i).addClass('animate').one('animationend', function () {
        setTimeout(function () {
            $(this).hide().show(0).addClass('reverse').one('animationend', function () {
                $(this).removeClass('animate');
                if(++i < $boxes.length) setTimeout(animateBox, 10000, i);
            });
        }.bind(this), 5000);
    });
})(0);
.box.animate {
    width: 200px;
    height: 200px;
    animation: box .6s ease-in;
}
.box.animate.reverse {
    animation-direction: reverse;
}
#red {
    background: red;
}
#green {
    background: green;
}
#blue {
    background: blue;
}
@keyframes box {
    0% {
        opacity: 0;
        transform: translateY(-40px);
    }
    100% {
        opacity: 1;
        transform: translateY(0px);
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container">
    <div id="red" class="box"></div>
    <div id="green" class="box"></div>
    <div id="blue" class="box"></div>
</div>

此处为无限循环:

(function animateBox(i) {
    $boxes.eq(i).addClass('animate').one('animationend', function () {
        setTimeout(function () {
            $(this).hide().show(0).addClass('reverse').one('animationend', function () {
                $(this).removeClass('animate reverse');
                setTimeout(animateBox, 10000, ++i < $boxes.length ? i : 0);
            });
        }.bind(this), 5000);
    });
})(0);

-jsFiddle sample-

(延迟更短)

关于javascript - 以暂停方式在循环中单独设置动画 Div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33200099/

相关文章:

javascript - 页面加载后向 <body> 添加元素的问题

javascript - 如何在 jQuery 中安排位置绝对 div

javascript - Google Autocomplete API - 格式化输出结果

PHP + CSS + Lettering.js 创建曲线文字

javascript - 如何使用 jquery 设置当前窗口大小和位置(因为 body onload 不适用于 asp.net)

javascript - 使用 css 固定列和固定标题和滚动文本?

php - JQuery .GET 调用/函数

html - 按钮有一个讨厌的居中问题

javascript - 进度条倒计时不起作用

javascript - 动态生成的数据网格控件删除链接中不会调用经典 ASP.NET 删除事件