防止CSS動畫在移除類別時停止的方法
P粉412533525
P粉412533525 2023-08-29 16:15:06
0
1
451
<p>我有一個網格。 當我從後端收到更新訊息時,我需要在3秒內用橙色突出顯示行。 當我收到更新時,我將css類'highlight'添加到我的行中並播放我的動畫。 </p> <p> <pre class="brush:css;toolbar:false;">.highlight { animation-name: highlight; animation-duration: 3s; } @keyframes highlight { 0% { background-color: orange; } 99.99% { background-color: orange; } }</pre> </p> <p>由於應用程式中訊息流的某些原因,我需要在3秒結束之前移除highlight類,這樣我的動畫就會停止工作。我希望我的動畫能一直播放到3秒結束。 </p> <p>如何讓我的動畫即使我刪除了highlight類別也能播放到結束? </p>
P粉412533525
P粉412533525

全部回覆(1)
P粉265724930

一種可能的方法是向元素添加一個data-屬性,然後向其添加一個animationend事件監聽器,以便在動畫完成時,事件監聽器知道要移除該類別。請參閱下面的範例。

document.getElementById('clicky').addEventListener('click', () => {
  const element=document.querySelector('.highlight');
  element.setAttribute('data-remove-class', 'highlight');
  element.innerHTML='将在动画结束时移除类';
});

document.querySelector('.highlight').addEventListener('animationend', (e) => {
  const removeClass = e.target.getAttribute('data-remove-class');
  if (removeClass == 'highlight') {
    e.target.classList.remove(removeClass);
    e.target.removeAttribute('data-remove-class');
    e.target.innerHTML='类已移除!';
  }
});
.highlight {
  animation-name: highlight;
  animation-duration: 3s;
}

@keyframes highlight {
  0% {
    background-color: yellow;
  }
  99.99% {
    background-color: orange;
  }
}
<div class='highlight'>正在动画中!</div>
<button id='clicky'>移除类</button>
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!