【问题标题】:Detect the end of specific CSS animation of an element检测元素的特定 CSS 动画的结束
【发布时间】:2020-01-10 09:09:25
【问题描述】:

我们有两个 CSS 动画关键帧,它们将使用 Javascript 添加或删除到元素:

通过从上到下设置动画来隐藏元素:

upperGuideText.classList.add("upperGuideAnimeHide"); // Hide CSS KeyFrames

另一个用于通过从下到上动画来显示元素:

upperGuideText.classList.add("upperGuideAnimeShow"); // Show CSS KeyFrames

我们只需通过类向元素添加和删除它们。

然后我们创建一个函数来处理这些显示和隐藏动画,命名为guideReveal。

每次我们调用guideReveal并将文本传递给函数时,都会有两个步骤:

首先,我们隐藏最后一个文本(动画从上到下)

然后我们添加并动画化刚刚传递给函数的新文本(动画从下到上)。

代码很简单,请看一下:

function guideReveal(text){

// Hide the `upperGuideText` on each guideReveal function execution
upperGuideText.classList.add("upperGuideAnimeHide"); // Hide CSS KeyFrames
upperGuideText.classList.remove("upperGuideAnimeShow"); // Show CSS KeyFrames

 // After a delay show another `upperGuideText`
  setTimeout(function(){
  upperGuideText.innerHTML = `${text}`;

  upperGuideText.classList.add("upperGuideAnimeShow"); // Show CSS KeyFrames
  upperGuideText.classList.remove("upperGuideAnimeHide"); // Hide CSS KeyFrames

  //Track end of only `upperGuideAnimeShow` animation! It's not working right now
  upperGuideText.addEventListener("webkitAnimationEnd", function(){
  console.log('Animation of guide ended..!')
  });

  }, 1000);
}

到目前为止,当文本显示和文本隐藏时,我们可以使用 webkitAnimationEnd 跟踪动画的结束,但是,我不想跟踪隐藏动画的结束...

我们怎样才能追踪到只有upperGuideAnimeShow动画的结尾!

【问题讨论】:

    标签: javascript css


    【解决方案1】:

    您可以查找animationend 事件的特定animationName 属性,例如

    let d = document.querySelector('div')
    d.addEventListener('animationend', function(ev) {
       if (ev.animationName === 'fade') {
         alert('end')
       }
    })
    div {
       margin: 100px;
       width: 100px;
       height: 100px;
       background: yellowgreen;
       animation: fade 5s linear 0s 1,
                  resize 2s linear 0s forwards;
       
    }
    
    @keyframes fade {
       from { opacity: 1 }
       to { opacity: 0 }
    }
    
    @keyframes resize {
       from { transform: scaleX(1) }
       to { transform: scaleX(2) }
    }
    <div></div>

    在此示例中,我设置了两个不同的动画,但在事件处理程序中,我检查了淡入淡出动画。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多