Javascript 转换一个接一个

标签 javascript html css-transitions

我想要做的是,如果用户再次按下按钮,则从头开始播放过渡。现在的问题是,如果用户单击按钮两次或两次以上,它将无法正确启动两个动画(一个接一个)。

所以现在转换正在工作,但如果用户多次单击按钮,我就很难做到这一点。

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)
}

实例https://jsfiddle.net/kzjpb55f/

最佳答案

每当收到新的点击事件时,使用 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/

相关文章:

javascript - 如何使用 google map api 获得精确位置?

javascript - getCurrentPosition 不适用于 angularjs

jquery - 如何即时提高 css 转换速度

html - 为什么 Mozilla Firefox 不支持我网站上的第三方字体?

html - 中心内联 block Div 不起作用

css - 为什么谷歌字体在 Chrome 中看起来那么糟糕?

css - 过渡运行时居中的 div 看起来不稳定

javascript - AngularJS:地理定位 + promise + $申请

javascript - 如何通过 javascript 或 jquery 获取下一行列

python - 如何使用 SEC 网站的 BeautifulSoup 的 getText() 方法忽略 HTML 中嵌入的 jpeg 图像数据