我有一些用 jQuery animate 制作的可重复使用的动画序列函数。我想并行运行其中两个,从同一点触发,并在两者完成时进行一次回调。关于我如何做到这一点有什么建议吗?
我想以并行方式运行的两个动画序列的简单示例如下:
function deleteel(element) {
element.parentNode.removeChild(element);
}
function animation1(inputcallback){
var div1 = document.createElement("div");
div1.style.position = "absolute";
div1.style.left = "0px";
div1.style.top = "0px";
div1.style.width = "10px";
div1.style.height = "10px";
div1.style.backgroundColor="red";
document.getElementById("animationcontainer").appendChild(div1);
$(div1).animate({top: "50"}, "slow", function() {
$(div1).animate({left: "+50"}, "slow", function() {
$(div1).animate({top: "20", left: "0"}, "slow", function() {
$(div1).animate({height: "50", top: "110", left: "0"}, "slow", function() {
$(div1).remove();
inputcallback();
});
});
});
});
}
function animation2(inputcallback){
var div1 = document.createElement("div");
div1.style.position = "absolute";
div1.style.left = "100px";
div1.style.top = "100px";
div1.style.width = "15px";
div1.style.height = "15px";
div1.style.backgroundColor="blue";
document.getElementById("animationcontainer").appendChild(div1);
$(div1).animate({top: "10"}, "fast", function() {
$(div1).animate({left: "+60"}, "slow", function() {
$(div1).animate({top: "200", left: "100"}, "slow", function() {
$(div1).animate({width: "50", top: "10", left: "100"}, "slow", function() {
$(div1).remove();
inputcallback();
});
});
});
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="animationcontainer" style="position:relative; width:500px; height:500px; background-color:grey"></div>
<button onclick="animation1(function () { alert('Finished');})">Animation 1</button>
<button onclick="animation2(function () { alert('Finished');})">Animation 2</button>
<button onclick="">Both animations</button>
最佳答案
首先从函数返回 promise 而不是使用回调
function animation1(){
var div1 = $("<div />", {
css : {
position : 'absolute',
left : '0px',
top : '0px',
width : '10px',
height : '10px',
background : 'red'
}
});
$("#animationcontainer").append(div1);
return div1.animate({top : "50" }, "slow")
.animate({left : "+50"}, "slow")
.animate({top : "20", left : "0" }, "slow")
.animate({height : "50", top : "110", left: "0"}, "slow")
.promise()
.done(function() {
$(this).remove();
});
}
然后添加适当的事件处理程序
$('#button1').on('click', function() {
animation1().done(function() {
alert('finished');
});
});
对于最后一个,要处理两个动画,您需要
$('#button3').on('click', function() {
$.when(animation1(), animation2()).done(function() {
alert('finished');
});
});
关于javascript - 当两个预构建的 jQuery 动画序列都完成时,如何通过一个回调并行运行它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27657613/