如何实现元素先bounceInDown后zoomOutDown的序列动画(无需jQuery)
如何在无jQuery的情况下实现序列动画?
嘿,我来帮你解决这个问题!你原来的代码无效是因为同一个元素不能重复定义相同的data-*属性——后面的data-os-animation和data-os-animation-delay会直接覆盖前面的,所以只有最后那个zoomOutDown动画会生效,而且延迟还是1秒,完全不是你想要的效果。
下面给你两种不需要jQuery的解决方案,你可以根据需求选择:
方案一:纯CSS实现(最简单)
如果你已经引入了Animate.css(看起来你是在用它的动画类),只需要给元素写一个自定义CSS类,把两个动画按顺序声明,设置好延迟和停留时间就行:
/* 自定义序列动画类 */ .animated-sequence { /* 第一个动画:bounceInDown,3秒后执行,时长1秒,停在最后一帧 */ /* 第二个动画:zoomOutDown,在第一个动画结束后停留2秒再执行(3+1+2=6秒延迟) */ animation: bounceInDown 1s ease 3s forwards, zoomOutDown 1s ease 6s forwards; }
然后修改你的HTML,把原来的os-animation相关属性换成这个自定义类:
<section class="animated-sequence"> <p id="helper">Filler Text</p> </section>
如果没有用Animate.css,你可以自己定义动画关键帧(完全原生):
/* 定义bounceInDown关键帧 */ @keyframes bounceInDown { from, 60%, 75%, 90%, to { animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1); } 0% { opacity: 0; transform: translate3d(0, -3000px, 0); } 60% { opacity: 1; transform: translate3d(0, 25px, 0); } 75% { transform: translate3d(0, -10px, 0); } 90% { transform: translate3d(0, 5px, 0); } to { transform: translate3d(0, 0, 0); } } /* 定义zoomOutDown关键帧 */ @keyframes zoomOutDown { 40% { opacity: 1; transform: scale3d(0.475, 0.475, 0.475) translate3d(0, -60px, 0); animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19); } to { opacity: 0; transform: scale3d(0.1, 0.1, 0.1) translate3d(0, 2000px, 0); transform-origin: center bottom; } } .animated-sequence { animation: bounceInDown 1s ease 3s forwards, zoomOutDown 1s ease 6s forwards; }
方案二:原生JS的Web Animations API(更灵活)
如果需要更精细的控制(比如动态调整停留时间、监听动画状态),可以用浏览器原生的Web Animations API,完全不需要jQuery:
<section> <p id="helper">Filler Text</p> </section> <script> const helperText = document.getElementById('helper'); // 执行第一个动画:bounceInDown,3秒延迟 const bounceAnimation = helperText.animate( [ { opacity: 0, transform: 'translate3d(0, -3000px, 0)' }, { opacity: 1, transform: 'translate3d(0, 25px, 0)', offset: 0.6 }, { transform: 'translate3d(0, -10px, 0)', offset: 0.75 }, { transform: 'translate3d(0, 5px, 0)', offset: 0.9 }, { transform: 'translate3d(0, 0, 0)' } ], { duration: 1000, // 动画时长1秒 delay: 3000, // 3秒后开始 easing: 'cubic-bezier(0.215, 0.61, 0.355, 1)', fill: 'forwards' // 动画结束后保持最后一帧状态 } ); // 第一个动画结束后,停留2秒再执行zoomOutDown bounceAnimation.onfinish = () => { setTimeout(() => { helperText.animate( [ { opacity: 1, transform: 'scale3d(0.475, 0.475, 0.475) translate3d(0, -60px, 0)', offset: 0.4 }, { opacity: 0, transform: 'scale3d(0.1, 0.1, 0.1) translate3d(0, 2000px, 0)', transformOrigin: 'center bottom' } ], { duration: 1000, easing: 'cubic-bezier(0.55, 0.055, 0.675, 0.19)', fill: 'forwards' } ); }, 2000); // 这里的2000就是停留的毫秒数,可随意调整 }; </script>
两种方法都能实现你想要的效果:3秒后执行bounceInDown,停留一段时间后执行zoomOutDown,完全不需要依赖jQuery~
内容的提问来源于stack exchange,提问作者JShepherd
相关产品推荐
相关产品推荐

