前一陣子在做 CSS 動畫的時候,遇到了特定情況會希望動畫重新開始的狀況

像是每點擊一次按鈕就觸發一次動畫的情境,查了一下相關的做法.記錄在這


舉個例子,我們有個 fade-in 的動畫,希望在點擊文字時重新開始動畫

<style>
@keyframes fade-in {        
  from {
    opacity : 0;
    left : -500px;
  }
  to {
    opacity : 1;
    left : 0;
  }      
}

.fade-in {
  position: relative;
  animation: fade-in 2s ease;
}
</style>
<h1 class="fade-in">
  Animation Text (click to restart)
</h1>

這時候你可能會很直覺認為再次添加 fade-in class ,像是以下這樣

See the Pen restart css animation by camel2243 (@camel2243) on CodePen.

然後你會發現不 work,於是直覺會想說那先做 removeadd XD

See the Pen css animation demo1 by camel2243 (@camel2243) on CodePen.

結果發現還是不會動,只好開 setTimeout 大絕 www

See the Pen css animation demo3 by camel2243 (@camel2243) on CodePen.

雖然看起來不是很好,但是 It’s works!

這邊另外提供一種比較取巧的方式:

  • 觸發瀏覽器重新 render

See the Pen css animation demo4 by camel2243 (@camel2243) on CodePen.

參考資料:

https://css-tricks.com/restart-css-animation/

Leave a Reply