CSS关键帧动画实现小球循环碰撞

位置: 首页 > 代码集锦
[发布: 2024.6.28  作者: 马黑  阅读: 29]

效果:

代码:

<style> #stage { --state: running; margin: 20px auto; padding: 6px 0; width: 600px; height: 40px; border: 1px solid gray; position: relative; } .ball { position: absolute; left: 0; width: 40px; height: 40px; border-radius: 50%; background: linear-gradient(pink, darkgreen); cursor: pointer; animation: 2s linear forwards var(--state); } #b1 { animation-name: move1; } #b2 { left: 300px; background: linear-gradient(plum, navy); } @keyframes move1 { from { transform: translate(0px); } to { transform: translate(260px); } } @keyframes move2 { from {transform: translate(260px); } to { transform: translate(0px); } } </style>   <div id="stage">     <div id="b1" class="ball"></div>     <div id="b2" class="ball"></div> </div>   <script> var running = true; //运行开关 //小球1动画结束 :处理俩球的动画名称 b1.onanimationend = () => {     var name = window.getComputedStyle(b1).getPropertyValue('animation-name');     if(name === 'move1') {         b1.style.animationName = '';         b2.style.animationName = 'move1';     }else{         b1.style.animationName = 'move1';     } }; //小球2动画结束 :处理俩球的动画名称 b2.onanimationend = () => {     var name = window.getComputedStyle(b2).getPropertyValue('animation-name');     if(name === 'move1') {         b2.style.animationName = 'move2';     }else{         b1.style.animationName = '';         b1.style.animationName = 'move2';     } }; //小球点击事件 :播放、暂停切换 b1.onclick = b2.onclick = () => {     stage.style.setProperty('--state', ['running','paused'][+running]);     running = !running; }; </script>

前一篇: 又一个漂亮的单标签音频播放器
下一篇: CSS关键帧动画文本效果:逐行出场(封装二)

发表评论:

  
 

评论列表 [1条]

#1 | 悄然 于 2024-6-28 15:59 发布: 又一个好玩的运动,点击小球可以暂停~~可以停在任意位置

Copyright © 2023 All Right Reserved 马黑PHP文章管理整站系统v1.8
联系我们: gxblk@163.com