javascript - 当 javascript 连续添加属性时,CSS 转换不起作用

标签 javascript html 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";
}
#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>

关于javascript - 当 javascript 连续添加属性时,CSS 转换不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53361920/

相关文章:

输出数组时Javascript未定义消息

javascript - Angular 1.7 绑定(bind)数据问题

javascript - "x is not defined"调用 javascript 函数时

html - CSS- 在线显示事物

html - 将 border-bottom 添加到嵌套列表项

html - 无法为显示的文本装饰获取多个值

javascript - 关闭 div - javascript 不工作

html - 内容容器下的 CSS 下拉菜单

jquery - body 塌陷时面板的头部不会塌陷

javascript - 按钮 onclick 事件在表数据的 innerHTML 中不起作用,同时使用按钮从本地存储中删除数据