【问题标题】:svg animation wont play again after clicking点击后svg动画不会再次播放
【发布时间】:2017-08-06 12:59:36
【问题描述】:

你好,我有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) 和头等舱一样。但是不行!你能帮帮我吗?

【问题讨论】:

    标签: jquery css svg jquery-animate keyframe


    【解决方案1】:

    问题是动画只会在该类中运行一次。为避免这种情况,您必须在动画完成后移除该类。

    您可以在这里找到答案: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");
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-02
      • 2021-09-16
      • 2019-03-11
      • 2021-04-27
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多