HTML:
<div id="my_div" class="all_divs"></div>
<div class="all_divs"></div>
<div class="all_divs"></div>CSS:
.all_divs {
width: 100px;
height: 100px;
background: #009;
margin-top: 10px;
opacity: 0;
}JS/JQUERY:
function light() {
$("#my_div").animate({opacity: 1}, 500, function() {
shutdown();
});
}
function shutdown() {
$("#my_div").animate({opacity: 0}, 500, function() {
light();
});
}
$(document).ready(function() {
light();
});当我尝试只动画一个div (id="my_div")时,它可以正常工作,尽管当我尝试使用$(".all_divs")动画所有3个元素时,动画崩溃了。
这是什么原因呢?
下面是一个例子,当选择器是类.all_divs时,动画崩溃:
https://jsfiddle.net/oL65jax0/
这是预期的结果:
发布于 2019-03-10 22:13:48
这是因为您的"on动画结束“回调为每个具有all_divs类的元素调用了light()和shutdown() (每次调用3次)。解决这个问题的一种方法是只为最后一个元素调用light()和shutdown()。
function light() {
$(".all_divs").animate({opacity: 1}, 500, function(i) {
if (this === $(".all_divs").last().get(0))
shutdown();
});
}
function shutdown() {
$(".all_divs").animate({opacity: 0}, 500, function() {
if (this === $(".all_divs").last().get(0))
light();
});
}
$(document).ready(function() {
light();
});.all_divs {
width: 100px;
height: 100px;
background: #009;
margin-top: 10px;
opacity: 0;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="my_div" class="all_divs" ></div>
<div class="all_divs" ></div>
<div class="all_divs" ></div>
或者你可以把最后一个元素保存在某个地方,这样你就不必重新计算它了。
function light() {
$(".all_divs").animate({opacity: 1}, 500, function(i) {
if (this === App.lastAnimatedElement)
shutdown();
});
}
function shutdown() {
$(".all_divs").animate({opacity: 0}, 500, function() {
if (this === App.lastAnimatedElement)
light();
});
}
var App = App || {};
$(document).ready(function() {
App.lastAnimatedElement = $(".all_divs").last().get(0);
light();
});.all_divs {
width: 100px;
height: 100px;
background: #009;
margin-top: 10px;
opacity: 0;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="my_div" class="all_divs" ></div>
<div class="all_divs" ></div>
<div class="all_divs" ></div>
https://stackoverflow.com/questions/55086324
复制相似问题