SVG圆形动画仅首次点击生效问题求助(附代码)
问题原因及解决方案
核心原因
jQuery的.animate()方法在初始化动画时,会先读取目标属性的当前值作为动画起始值,之后才执行start回调。第一次动画完成后,圆形的cx属性已经变为200,第二次点击按钮时:
- jQuery先读取
cx=200作为动画起始值 - 随后执行
start回调将cx设为100,但动画逻辑已经锁定了起始值为200,目标值也是200,自然看不到动画效果。
解决方案
方案1:提前重置起始位置(最直接)
把设置cx=100的操作放在.animate()调用之前,确保jQuery读取起始值时已经是正确的初始位置:
$(function() { $("button").click(function() { console.log('Button click'); const currentBallCircle = $("#currentBallCircle"); // 先重置到起始位置 currentBallCircle.attr("cx", "100"); currentBallCircle.animate({ cx: "200" // 目标位置 }, { duration: 1000, complete: function() { console.log('Animation completed!'); } }); }); });
方案2:清空动画队列(避免冲突)
如果存在未完成的动画残留,先停止并清空队列,再重置位置执行动画:
$(function() { $("button").click(function() { console.log('Button click'); const currentBallCircle = $("#currentBallCircle"); // 停止所有未完成动画,清空队列并跳转到动画结束状态 currentBallCircle.stop(true, true) .attr("cx", "100") .animate({ cx: "200" }, { duration: 1000, complete: function() { console.log('Animation completed!'); } }); }); });
方案3:使用原生SVG动画(更适配SVG)
原生SVG的<animate>元素专门针对SVG属性设计,动画逻辑更可靠:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script> <button>Start Animation</button> <svg height="200"> <circle id="currentBallCircle" r="30" cy="50" cx="100" stroke-width="2" fill="blue"> <animate id="circleAnim" attributeName="cx" from="100" to="200" dur="1s" begin="indefinite" fill="freeze"/> </circle> </svg> <script> $(function() { $("button").click(function() { console.log('Button click'); // 重置并触发动画 const animElement = document.getElementById('circleAnim'); animElement.beginElement(); }); }); </script>
内容的提问来源于stack exchange,提问作者Arne Laugstøl
相关产品推荐
相关产品推荐

