如何使用 Javascript vanilla 为元素设置动画?与 jquery 类似。例子:
$( "button.continue" ).animate({left: "100px", top: "200px"}, 5000);
我们在何处传递属性、所需值和时间。
在我的情况下,我需要左侧和顶部位置来制作动画和滑动。
解决方案
我已经完成了@IceMetalPunk sugested 并仅在需要动画时才通过 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>
潇湘沐
交互式爱情
慕尼黑5688855
翻阅古今
随时随地看视频慕课网APP
相关分类