我想要做的是,如果用户再次按下按钮,则从头开始播放过渡。现在的问题是,如果用户单击按钮两次或两次以上,它将无法正确启动两个动画(一个接一个)。
所以现在转换正在工作,但如果用户多次单击按钮,我就很难做到这一点。
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)
}
最佳答案
每当收到新的点击事件时,使用 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>
关于Javascript 转换一个接一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45357130/