使用 Javascript vanilla 动画元素

如何使用 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>


潇湘沐
浏览 249回答 3
3回答

交互式爱情

尝试使用 CSS 过渡。在 CSS 中,做这样的事情:button.continue {&nbsp; transition: 5s;}然后在 JS 中,你可以只设置左/上值:document.querySelectorAll('button.continue').forEach(button => {&nbsp; button.style.left = '100px';&nbsp; button.style.top = '200px';});

慕尼黑5688855

在 Firefox 中测试。document&nbsp; &nbsp;.querySelector(".text.thank-you")&nbsp; &nbsp;.animate({ opacity: [0, 1] }, { duration: 5000, iterations: 1, easing: "ease-out" })&nbsp; &nbsp;.onfinish = (e) => {&nbsp; &nbsp; &nbsp; &nbsp; e.target.effect.target.style.opacity = 1;&nbsp; &nbsp;};

翻阅古今

尝试使用WebComponents,您可以执行只使用任何类型的动画VanillaJS,有预定义如动画Animate.css,但你可以通过创建自定义动画关键帧:<!-- Add Web Animations Polyfill :) --><script src="https://cdnjs.cloudflare.com/ajax/libs/web-animations/2.3.2/web-animations.min.js"></script><script type="module" src="https://unpkg.com/@proyecto26/animatable-component@1.0.0/dist/animatable-component/animatable-component.esm.js"></script><script nomodule="" src="https://unpkg.com/@proyecto26/animatable-component@1.0.0/dist/animatable-component/animatable-component.js"></script><animatable-component&nbsp; autoplay&nbsp; easing="ease-in-out"&nbsp; duration="1200"&nbsp; delay="300"&nbsp; animation="heartBeat"&nbsp; iterations="Infinity"&nbsp; style="display: flex;align-self: center;">&nbsp; <h1>Hello World</h1></animatable-component>有关更多详细信息,请查看此处:https : //github.com/proyecto26/animatable-component
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript