2017-03-15 98 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

爲什麼您刪除此解決方案的「接受」? –