2017-03-15 100 views
1

后再次打个招呼,我有this fiddleSVG动画不会点击

$('button').click(function(){ 
 
\t $('#sa').addClass('animate-sa2') 
 
})
\t \t .st0{fill:none;stroke:#000000;stroke-width:33;stroke-miterlimit:10;}; 
 
    #sa{ 
 
\t \t \t stroke-dasharray:320; 
 
\t \t \t stroke-dashoffset:100; 
 
\t \t \t } 
 
    .animate-sa{ 
 
\t  animation:1.5s animate-sa forwards; 
 
     } 
 
     .animate-sa-2{ 
 
\t  animation:1.5s animate-sa forwards; 
 
     } 
 
     \t @keyframes animate-sa{ 
 
\t \t from{ 
 
\t \t \t \t stroke-dasharray:320; 
 
\t \t \t \t stroke-dashoffset:100; 
 
\t \t \t } 
 
\t \t \t to{ 
 
\t \t \t \t stroke-dasharray:500; 
 
\t \t \t \t stroke-dashoffset:0; 
 
\t \t \t } 
 
     }
<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 
 
       \t s-21.2,77.8,32.9,70.8c53.2-6.9,7.6-93.5,7.6-93.5"/> 
 
        
 
    </svg>

SVG将动画立刻上因为类的页面加载( “动画-SA”),但我在这里有一个按钮,它应该通过添加(“animate-sa2)”,它与第一类相同,但它不起作用!你能帮我吗?

回答

1

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

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

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

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

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"); 
    }); 
}); 
+0

为什么您删除此解决方案的“接受”? –