以下是我在网站上遇到的问题的简化版本。
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/