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

CSS transition doesn't work when javascript added properties continuous

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

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";
}
#box{
  width:100px;
  height:100px;
  background:red;
  position:relative;
  top:0px;
}
<div id="box" onclick="move()"></div>

我想让它做的是让盒子瞬间向下跳,然后慢慢回到起始位置。我已经分别测试了 move() 中的四行代码,它们运行良好。我就是没法一下子把它们弄到 运行。

我做错了什么?

似乎代码需要在分配新 属性 之前延迟,这会导致浏览器可以处理请求。所以你需要使用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);
}
#box{
  width:100px;
  height:100px;
  background:red;
  position:relative;
  top:0px;
}
<div id="box" onclick="move()"></div>

与其依赖转换,不如使用 @keyframesanimation,这样您就不必使用肮脏的技巧,例如将转换持续时间从 0 更改为实际值中间动画实现跳跃。下面是一个利用 @keyframes css 特性的例子:

function move(){
  document.getElementById("box").style.animation = "movement 2s";
}
#box{
  width:100px;
  height:100px;
  background:red;
  position:relative;
  top:0px;
}
@keyframes movement {
    from {top: 100px;}
    to {top: 0px;}
}
<div id="box" onclick="move()"></div>