为了账号安全,请及时绑定邮箱和手机立即绑定

使用 Javascript vanilla 动画元素

使用 Javascript vanilla 动画元素

潇湘沐 2021-11-12 15:29:57
如何使用 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>
查看完整描述

3 回答

?
交互式爱情

TA贡献1712条经验 获得超3个赞

尝试使用 CSS 过渡。在 CSS 中,做这样的事情:


button.continue {

  transition: 5s;

}

然后在 JS 中,你可以只设置左/上值:


document.querySelectorAll('button.continue').forEach(button => {

  button.style.left = '100px';

  button.style.top = '200px';

});


查看完整回答
反对 回复 2021-11-12
?
慕尼黑5688855

TA贡献1848条经验 获得超2个赞

在 Firefox 中测试。


document

   .querySelector(".text.thank-you")

   .animate({ opacity: [0, 1] }, { duration: 5000, iterations: 1, easing: "ease-out" })

   .onfinish = (e) => {

        e.target.effect.target.style.opacity = 1;

   };


查看完整回答
反对 回复 2021-11-12
?
翻阅古今

TA贡献1780条经验 获得超5个赞

尝试使用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

  autoplay

  easing="ease-in-out"

  duration="1200"

  delay="300"

  animation="heartBeat"

  iterations="Infinity"

  style="display: flex;align-self: center;"

>

  <h1>Hello World</h1>

</animatable-component>


有关更多详细信息,请查看此处:https : //github.com/proyecto26/animatable-component


查看完整回答
反对 回复 2021-11-12
  • 3 回答
  • 0 关注
  • 248 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号