jquery - 单击后 svg 动画不会再次播放

标签 jquery css svg jquery-animate keyframe

你好,我有 this fiddle

$('button').click(function(){
	$('#sa').addClass('animate-sa2')
})
		 .st0{fill:none;stroke:#000000;stroke-width:33;stroke-miterlimit:10;};
    #sa{
			stroke-dasharray:320;
			stroke-dashoffset:100;
			}
     .animate-sa{
	      animation:1.5s animate-sa forwards;
      }
        .animate-sa-2{
	      animation:1.5s animate-sa forwards;
      }
      	@keyframes animate-sa{
		from{
				stroke-dasharray:320;
				stroke-dashoffset:100;
			}
			to{
				stroke-dasharray:500;
				stroke-dashoffset:0;
			}
      }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button type="button">click</button>

    <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"         x="0px" y="0px" width="501.9px" height="273.8px" viewBox="0 0 501.9 273.8" style="enable-background:new 0 0 501.9     273.8;" xml:space="preserve">
    
    
                <path  id="sa" class="animate-sa st0 " d="M281,156.2c56,51.5,80.4-57.4,80.4-57.4c-12.5,41.2-9.2,71,19.2,71.6c28.4,0.6,43.7-71.2,43.7-71.2
                	s-21.2,77.8,32.9,70.8c53.2-6.9,7.6-93.5,7.6-93.5"/>
                  
     </svg>

由于 ("animate-sa") 类,svg 将在页面加载时立即 设置动画,但我这里有一个按钮,应该通过添加 再次设置它的动画>("animate-sa2) 与第一类相同。但它不起作用!你能帮我吗?

最佳答案

问题是动画只会用那个类运行一次。为避免这种情况,您必须在动画完成时删除该类。

您可以在这里找到答案:https://jonsuh.com/blog/detect-the-end-of-css-animations-and-transitions-with-javascript/

我用我的解决方案创建了一个 CodePen: http://codepen.io/interactivejohn/pen/NpadGy

首先我们检测动画事件,然后一旦该事件完成,我们就删除该类。在页面加载时初始动画发生后,我们首先将其删除。下次运行时(单击按钮后),它将添加该类,然后再次将其删除。

function whichAnimationEvent(){
  var t,
      el = document.createElement("fakeelement");

  var animations = {
    "animation"      : "animationend",
    "OAnimation"     : "oAnimationEnd",
    "MozAnimation"   : "animationend",
    "WebkitAnimation": "webkitAnimationEnd"
  }

  for (t in animations){
    if (el.style[t] !== undefined){
      return animations[t];
    }
  }
}

var animationEvent = whichAnimationEvent();

$("path").one(animationEvent,
              function(event) {
    // Do something when the transition ends
    $(this).removeClass("animate-sa");
});

$("button").click(function(){
  $("path").addClass("animate-sa");
  $("path").one(animationEvent,
              function(event) {
    // Do something when the transition ends
    $(this).removeClass("animate-sa");
  });
});

关于jquery - 单击后 svg 动画不会再次播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42815680/

相关文章:

jquery - 如何使用 jQuery Google Map UI v3 平移到某个点或标记?

javascript - 在 backstretch 上叠加内容

javascript - 如何在单击按钮时复制 URL?

html - IE有时会显示表格行边框

c# - 删除另一个进程正在使用的图像

html - 如何在 HTML 中创建泪珠?

javascript - 使用 jquery 将 PHP 脚本打印为纯文本

jquery - 在悬停时突出显示具有多个 div 的 td,取消突出显示其中一个 div

jquery - 使用带有动画的按钮显示不同的形式

CloudFront 中内容类型错误的 SVG 文件