如何实现点击Hit按钮触发CSS Keyframe动画使箭头触碰圆圈并变色?
实现点击按钮后箭头动画移动触碰圆圈并变色的解决方案
需求:点击Hit按钮时,箭头通过CSS Keyframe动画移动并触碰圆圈,同时圆圈颜色变为绿色;点击Reset按钮恢复圆圈颜色和箭头位置。原代码尝试后未成功,作为JavaScript新手对Keyframe和相关逻辑不熟悉。
问题分析
原代码存在几个核心问题:
- 箭头元素未设置
id="arrow",导致JavaScript无法获取节点 - CSS动画默认自动播放,不符合点击触发的交互逻辑
- Keyframe未定义有效的移动路径,箭头无法移动到圆圈位置
- 碰撞检测时机错误:点击按钮后立即检测,而非动画结束时
完整实现代码
HTML(修正箭头ID)
<body> <h1>Bubble App</h1> <section class="container"> <div class="circle" id="circle"></div> <div class="icon-arrow" id="arrow"></div> </section> <div class="button" role="button"> <button onclick="hit()">Hit</button> <button onclick="reset()">Reset</button><br> </div> </body>
CSS(调整动画触发逻辑与移动路径)
.container { border: 3px solid black; height: 60vh; width: 90vh; margin: auto; display: flex; justify-content: space-between; align-items: center; } h1 { text-align: center; } .circle { width: 100px; height: 100px; border-radius: 50%; background-color: blue; margin-left: 12px; } .icon-arrow { width: 90px; height: 3px; background-color: black; border-radius: 2px; position: relative; margin-right: 12px; /* 默认暂停动画,点击后启动 */ animation: moveArrow 1s forwards paused; } .icon-arrow:after { content: ''; display: inline-block; width: 30px; height: 2px; background-color: black; transform: rotate(45deg); position: absolute; left: -5px; top: 11px; } .icon-arrow:before { content: ''; display: inline-block; width: 30px; height: 2px; background-color: black; transform: rotate(-45deg); position: absolute; right: 65px; bottom: 9px; } .button { float: right; margin-right: 260px; padding-top: 9px; width: 20%; border-radius: 3px; } .button button { width: 20%; color: white; background-color: grey; margin-right: 16px } /* 定义箭头移动到圆圈位置的动画 */ @keyframes moveArrow { to { /* 计算向左移动的距离,确保箭头触碰圆圈 */ transform: translateX(calc(-90vh + 100px + 90px + 24px + 6px)); } }
JavaScript(控制动画触发与状态重置)
function hit() { const circle = document.getElementById('circle'); const arrow = document.getElementById('arrow'); // 重置动画状态,避免重复点击导致的异常 arrow.style.animation = 'none'; void arrow.offsetWidth; // 强制触发重绘 arrow.style.animation = ''; // 启动动画 arrow.style.animationPlayState = 'running'; // 动画结束时修改圆圈颜色 arrow.addEventListener('animationend', function handleAnimationEnd() { circle.style.backgroundColor = 'green'; // 移除事件监听,防止重复触发 arrow.removeEventListener('animationend', handleAnimationEnd); }); } function reset() { const circle = document.getElementById('circle'); const arrow = document.getElementById('arrow'); // 恢复圆圈颜色 circle.style.backgroundColor = 'blue'; // 重置箭头位置与动画状态 arrow.style.animationPlayState = 'paused'; arrow.style.transform = 'translateX(0)'; }
核心逻辑说明
- 使用
animation-play-state控制动画的播放/暂停,实现点击触发 - 动画添加
forwards属性,让箭头停在动画结束位置 - 监听
animationend事件,确保箭头到达位置后再修改圆圈颜色 - 重置函数同时恢复箭头初始位置和动画状态
内容的提问来源于stack exchange,提问作者user21878286
相关产品推荐
相关产品推荐

