我如何等待该动画完成后再继续下一个动画?

Hum*_*end 5 html javascript css animation

我正在使用 HTML、CSS 和 JavaScript 创建游戏。我有 5 个小时,我想等待动画完成后再继续执行代码的任何部分。动画按照我想要的方式工作,但 JavaScript 在第一个动画完成之前就开始下一个动画了!我尝试过使用

window.setTimeOut
Run Code Online (Sandbox Code Playgroud)

但没有运气。这是包含所需代码的代码: https: //codepen.io/HumanFriend/pen/mdOBvoL 有人可以帮助我吗?

ent*_*tio 7

您可以收听animationend事件,fe:

const animated = document.querySelector('.animated');

animated.addEventListener('animationend', () => {
  console.log('Animation ended');
});
Run Code Online (Sandbox Code Playgroud)

了解更多:https ://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/animationend_event


随机的事情:

使用时,setTimeout(nextI_ifelse(), 5000);只需调用 nextI_ifelse 内联(并且为此函数返回的值设置超时)。将其更改为setTimeout(nextI_ifelse, 5000);

任何您只想阅读一般算法的内容。你试图做的事情是有意义的,但你试图实现这一目标的方式却没有意义。codepen 中的 for 循环会立即运行,因此iLevel直接设置为最后一个值。


Jef*_*des 2

为了详细说明 entio 的答案,当元素具有“打字效果”类时,动画就会发生。当该动画结束时,浏览器会调用一个名为“animationend”的事件。您可以使用 JavaScript 通过访问该事件在下一个元素上运行动画。

请注意下面的 HTML 代码片段,我已将“display:hidden”移至 CSS 类并删除了“打字效果”。在我的 JavaScript 函数中,我启用第一个元素中的类,递增计数器,并告诉“animationend”使用“i”的新值再次调用该函数。

编辑:我忘了提及,我修改了 id 值。我不相信 HTML5 中的有效 id 值可以包含括号。

console.log("script.js connected");

let iLevel = 1;
let loop = 0;

function animateNext(i){
  let stop = document.querySelectorAll('.animated').length;
  let animated = document.querySelector(`#h2_${i}`);
  animated.classList.add('typing-effect');

  animated.addEventListener('animationend', () => {
    if(i===stop){
      iLevel = "iDone";
    }else{
      animateNext(i+1);
    }
  });
}

function startGame() {
  animateNext(1);
}
Run Code Online (Sandbox Code Playgroud)
.animated{
  display: none;
}
.typing-effect {
  display: block;
  animation: typing-effect 5s steps(130, end), 0.75s step-end infinite;
  white-space: nowrap;
  overflow: hidden;
  border-right: 2px solid black;
}
.typing-effect:after {
  content: " ";
}
@keyframes typing-effect {
  0% {
    width: 0%;
  }
  100% {
    width: 100%;
  }
}
@keyframes blink-caret {
  from,
  to {
    border-color: transparent;
  }
  50% {
    border-color: black;
  }
}
Run Code Online (Sandbox Code Playgroud)
<button onclick="startGame();">START GAME</button>

<div id="instructions">

  <div>
    <h2 id="h2_1" class="animated">Welcome to The Number Wizrd</h2>
  </div>

  <div>
    <h2 id="h2_2" class="animated">Adjfosdf</h2>
  </div>
  <div>
    <h2 id="h2_3" class="animated">sosidjfs</h2>
  </div>
  <div>
    <h2 id="h2_4" class="animated">difjspodf</h2>
  </div>
  <div>
    <h2 id="h2_5" class="animated">skidjfosidf</h2>
  </div>

</div>
Run Code Online (Sandbox Code Playgroud)