如果用户再次按下按钮,我想要做的是从头开始转换。现在的问题是,如果用户点击两次或更多按钮,它将无法正确启动两个动画(一个接一个)。
所以现在转换工作正常,但如果用户多次点击按钮,我就无法正常工作。
let button = document.querySelector("button")
let box = document.querySelector(".box")
button.onclick = () => {
box.style.transform = "";
anim1(function(){
anim2(function() {
})
})
}
function anim1(cb) {
box.style.transition = ""
box.clientHeight;
box.style.transition = "all 1s";
box.style.transform = "translateX(50px)";
setTimeout(() => {
cb()
},1000)
}
function anim2(cb) {
box.style.transition = ""
box.clientHeight;
box.style.transition = "all 1s";
box.style.transform = "translateX(350px)";
setTimeout(() => {
cb()
},1000)
}
答案 0 :(得分:1)
每当您收到新的点击事件时,都会使用clearTimeout
清除待处理的超时:
let button = document.querySelector("button")
let box = document.querySelector(".box")
let timer; // use this variable to trace any pending timeout
button.onclick = () => {
clearTimeout(timer); // clear any pending timeout
box.style.transform = "";
anim1(function(){
anim2(function() {
})
})
}
function anim1(cb) {
box.style.transition = ""
box.clientHeight;
box.style.transition = "all 1s";
box.style.transform = "translateX(50px)";
timer = setTimeout(cb,1000); // remember last created timeout
}
function anim2(cb) {
box.style.transition = ""
box.clientHeight;
box.style.transition = "all 1s";
box.style.transform = "translateX(350px)";
timer = setTimeout(cb,1000); // remember last created timeout
}

.box {
height:50px;
width:50px;
background-color:red;
}

<button>animate</button>
<div class="box"></div>
&#13;
答案 1 :(得分:0)
您可以简单地添加另一个变量,如果当前正在运行动画,则该变量为true,否则为false。
我updated your fiddle以及如何执行此操作的示例。
let button = document.querySelector("button")
let box = document.querySelector(".box")
let animating = false;
button.onclick = (e) => {
if (!animating) {
box.style.transform = "";
animating = true;
anim1(function(){
anim2(function() {
animating = false;
})
})
}
}
function anim1(cb) {
box.style.transition = ""
box.clientHeight;
box.style.transition = "all 1s";
box.style.transform = "translateX(50px)";
setTimeout(() => {
cb()
},1000)
}
function anim2(cb) {
box.style.transition = ""
box.clientHeight;
box.style.transition = "all 1s";
box.style.transform = "translateX(350px)";
setTimeout(() => {
cb()
},1000)
}