近來在製作 CSS 動畫時,遇到需要用腳本「重新播放」動畫的情況。直覺做法是移除再重新加上動畫 class,但實測會發現一個惱人的問題:第一次顯示時動畫正常播放,第二次卻不動了。本文記錄問題與解法。
.seed_txt_out .seed_txt h2 {
animation-name: seed-h2;
animation-duration: 2s;
animation-timing-function: ease;
animation-delay: 0s;
animation-iteration-count: 1;
animation-direction: alternate;
animation-play-state: running;
position: relative;
top: 10px;
}
@keyframes seed-h2
{
from {top: -120px;}
to {top: 10px;}
}
$(".seed_txt_out").children("div").removeClass("seed_txt");
$(".seed_txt_out").children("div").addClass("seed_txt");
這時會發現:第一次顯示動畫會正確播放,但第二次就不會了。這是因為瀏覽器在同一次 reflow 中移除又加入相同 class,並不會真正重置動畫狀態。
上網查詢後發現解法很簡單:複製一個元素,把原來的移除,再在新元素上套用樣式即可。
$(opts.txt).children("div").removeClass("seed_txt");
temp = $(opts.txt).children("div:eq(" + $(this).parent("ul").children("li").index(this) + ")");
newDiv = temp.clone(true);
temp.after(newDiv);
temp.remove();
newDiv.addClass("seed_txt");
這裡提供一個國外作者的相關討論連結,裡面還談到了其他情境,遇到類似問題的朋友可以參考(內容為英文):
https://css-tricks.com/restart-css-animation/