详细信息
我有一个里面有动画的功能,当点击按钮时,它会从.append
到div
再到body
。div
将使其位置向下移动一点。当添加另一个时,所有div
也将向下移动,因此它们不会重叠。
现在我们遇到了问题!当滥发创建div
的按钮时,它们将重叠。
我们如何才能阻止这种情况的发生?
注意:
- 因此,只有当最后一个函数完成了所有动画后,才能开始下一个调用
- 需要记住并运行函数单击按钮的次数
- 我的插件中的函数有需要记住的选项(例如弹出窗口的背景颜色(
我尝试了什么
我的看法是,我想创建一个队列,记录您单击按钮的次数,并在x经过一定时间(足以完成所有动画(后释放下一行。问题是我在jQuery中找不到这样做的方法。
- 我已经研究过在jQuery中使用
.queue
,但没有找到方法这可以帮助解决这个问题 - 我在函数上加了一个
setTimeout
,但这会导致点击延迟
我觉得这是一件非常简单的事情,但我自己折腾了几个小时后却找不到解决方案。
演示
我已经为这个问题创建了一个演示,我的真实版本是一个插件,所以它有自己的功能。这只是一个非常基本的版本。
$("button").click(function() {
$("body").append("<div></div>");
$($("div").get().reverse()).each(function(index) {
$(this).animate({
top: "+=120px"
}, {
duration: 600,
queue: false
});
if (index >= 2) {
// Fade out and then remove the item
$(this).fadeOut("fast", function() {
$(this).remove();
});
}
});
});
div {
width: 400px;
height: 50px;
background: rgba(0, 0, 0, .4);
position: absolute;
top: 0;
right: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click</button>
JSFiddle演示
试试这个解决方案。。。。阻止动画,直到动画回调
animated = false;
$("button").click(function() {
if(animated)
return false;
else
animated = true;
$("body").append("<div></div>");
$($("div").get().reverse()).each(function(index) {
$(this).animate({
top: "+=120px",
duration: 600,
queue: false
},function(){ animated = false; });
if (index >= 2) {
// Fade out and then remove the item
$(this).fadeOut("fast", function() {
$(this).remove();
});
}
});
});
div {
width: 400px;
height: 50px;
background: rgba(0, 0, 0, .4);
position: absolute;
top: 0;
right: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click</button>
这可能是管理动画队列的起点。
看看这个小提琴
向队列添加动画:
var freeToAnimate = true;
var animationQueue = [];
var i = 0;
$("button").click(function () {
var queueLength = animationQueue.length;
animationQueue.push(i);
i++;
if(queueLength == 0){
animateDivs(i-1);
} else {
return false;
}
});
function animateDivs(animationIndex) {
if(freeToAnimate == true) {
freeToAnimate = false;
var divsAmount = $("div").length;
$("body").append("<div></div>");
$($("div").get().reverse()).each(function(index, el) {
if(index >= 2) {
// Fade out and then remove the item
$(this).fadeOut( "fast", function() {
$(this).remove();
});
}
$(this).animate({
top: "+=120px"
}, 1200, function() {
var indx = animationQueue.indexOf(animationIndex);
animationQueue.splice(indx, 1);
if(index == divsAmount-1 || divsAmount == 0) {
freeToAnimate = true;
if(animationQueue.length != 0) {
animateDivs(animationIndex+1);
}
}
});
});
}
}
https://jsfiddle.net/4zwmm20e/12/