【发布时间】:2019-10-07 19:16:46
【问题描述】:
如何使用 Javascript vanilla 为元素制作动画? 与 jquery 类似。示例:
$( "button.continue" ).animate({left: "100px", top: "200px"}, 5000);
我们在哪里传递属性、期望的值和时间。
在我的情况下,我需要左侧和顶部位置来设置动画和滑动。
解决方案
我已经按照@IceMetalPunk 的建议完成了,只有在我需要动画时才通过 css 添加动画。
document.getElementById("animate").addEventListener("click", function(){
let e = document.getElementById('elementToAnimate');
e.classList.add("animate");
setTimeout(()=> e.classList.remove("animate"), 500);
e.style.top = Math.floor(Math.random() * window.innerHeight) + 'px';
e.style.left = Math.floor(Math.random() * window.innerWidth) + 'px';
});
document.getElementById("dontAnimate").addEventListener("click", function(){
let e = document.getElementById('elementToAnimate');
e.style.top = Math.floor(Math.random() * window.innerHeight) + 'px';
e.style.left = Math.floor(Math.random() * window.innerWidth) + 'px';
});
#elementToAnimate {
width: 20px;
height: 20px;
background: red;
position: absolute;
top: 0;
left: 0;
}
#elementToAnimate.animate {
transition: left 500ms ease-in-out, top 500ms ease-in-out;
}
<div id="elementToAnimate"></div>
<button id="animate">Animate</button>
<button id="dontAnimate">Dont Animate</button>
【问题讨论】:
-
为什么不用 CSS 呢?
-
@SebastianSimon 我不想每次都制作动画,如果我在元素中插入
transition,它会在每次更改其left和top位置时制作动画
标签: javascript animation