【问题标题】:An Javascript if statement for a keyframes in CSS?CSS中关键帧的Javascript if语句?
【发布时间】:2021-08-06 06:44:46
【问题描述】:

我一直在互联网上搜索,但找不到答案。

基本上,我想在 javascript 中做一个 if 语句...一旦 CSS3 中的关键帧动画达到 100%,就做一些动作。我只是不知道使用什么语法。

非常感谢您提供的任何帮助。

CSS3:

@keyframes progress-animation{
0%{
    width: 0%;
}

100%{
    width: 100%;
}
}

@keyframes loader {
0% {
  transform: rotate(0deg);
}

25% {
  transform: rotate(180deg);
}

50% {
  transform: rotate(180deg);
}

75% {
  transform: rotate(360deg);
}

100% {
  transform: rotate(360deg);
}

}

我想做什么(用文字):

if (progress-animation == '100%')
    stop animation (loader)

对不起,如果这是一个非常简单的答案;我对 Javascript 有点陌生。

【问题讨论】:

  • 看看animationend事件。 w3schools.com/jsref/event_animationend.asp
  • 真的应该没必要停止动画了。也许您可以添加 progress-animation 所在的 CSS?它应该在达到您设置的持续时间的 100% 时停止,除非您将其设置为无限。
  • 嘿,抱歉,有一个错字,我的意思是停止另一个关键帧动画,而不是同一个。刚刚更新,谢谢!

标签: javascript css animation conditional-statements css-animations


【解决方案1】:

您可以使用animationend 事件。

您还可以使用从事件接收到的animationName 参数添加条件,以仅检查特定动画。

这是一个演示:

const element = document.querySelector('.progress')
element.addEventListener("animationend", onAnimationComplete);

function onAnimationComplete(e){
  if(e.animationName==='progress-animation'){
     console.log("progress-animation ended")
  }
}
.progress{
  background:red;
  padding:10px;
  width:100px;
  border:solid 1px black;
  border-radius:16px;
  animation: progress-animation linear 3s;
}
@keyframes progress-animation{
  0%{
  width:0px;
  }
  100%{
   width:100px;
 }
}
<div class='progress'>

</div>

【讨论】:

    【解决方案2】:

    使用This guide

    你可以使用类似下面的东西:

    let style = document.getElementById('WhateverElementIsCalled').style;
    if(style[progress-animation] === '100%') {
        //Do a thing
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-03
      • 2020-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-11
      相关资源
      最近更新 更多