当 javascript 添加连续属性时,CSS 过渡不起作用

Jon*_*ers 3 html javascript css animation transition

以下是我的网站遇到的问题的简化版本。

function move(){
  document.getElementById("box").style.transition = "0s";
  document.getElementById("box").style.top = "100px";
  document.getElementById("box").style.transition = "2s";
  document.getElementById("box").style.top = "0px";
}
Run Code Online (Sandbox Code Playgroud)
#box{
  width:100px;
  height:100px;
  background:red;
  position:relative;
  top:0px;
}
Run Code Online (Sandbox Code Playgroud)
<div id="box" onclick="move()"></div>
Run Code Online (Sandbox Code Playgroud)

我想让它做的是让盒子瞬间向下跳跃,然后慢慢移回到起始位置。我已经分别测试了里面的四行代码move(),它们工作得很好。我就是没法让他们一口气跑掉。

我究竟做错了什么?

Moh*_*mad 5

看来代码需要在分配新属性之前延迟,以使浏览器可以处理请求。所以你需要使用setTimeout()来解决这个问题。

function move(){
  document.getElementById("box").style.transition = "0s";
  document.getElementById("box").style.top = "100px";
  setTimeout(function(){
    document.getElementById("box").style.transition = "2s";
    document.getElementById("box").style.top = "0px";
  }, 10);
}
Run Code Online (Sandbox Code Playgroud)
#box{
  width:100px;
  height:100px;
  background:red;
  position:relative;
  top:0px;
}
Run Code Online (Sandbox Code Playgroud)
<div id="box" onclick="move()"></div>
Run Code Online (Sandbox Code Playgroud)