可以在关键帧末尾调用函数吗?

问题描述 投票:0回答:1

我正在用 HTML/JS/CSS 制作一个游戏,它在顶部有一种新闻系统,文本在屏幕上滚动,一旦到达末尾,新的文本字符串就会开始滚动。我让它生成新字符串的方法是使用 setTimeout 每 20 秒更改一次。大多数情况下,这种方法效果很好,但有时关键帧动画和 setTimeout 会不同步(来自浏览器通知、切换选项卡、切换窗口等)。这会导致消息在关键帧动画中途发生变化,并且保持不同步,除非稍后同步。

我尝试寻找在CSS关键帧动画结束时调用JS函数的方法,但我没有找到任何东西。

javascript html css
1个回答
0
投票

您可以采取的一种方法是将 JavaScript 超时与 CSS 动画同步

function changeNewsText() {
  // Change the news text here
}

// Get the duration of the CSS animation
const animationDuration = 10; // 10s in this case, adjust as needed

// Set the timeout to fire just after the animation duration
setTimeout(function() {
  changeNewsText();
  // Call this function recursively to keep changing the news text
  setTimeout(arguments.callee, animationDuration * 1000);
}, animationDuration * 1000);
#newsTicker {
  width: 100%;
  height: 50px;
  overflow: hidden;
  position: relative;
}

#newsText {
  position: absolute;
  animation: newsScroll 10s linear infinite;
}

@keyframes newsScroll {
  0% { transform: translateX(100%); }
  100% { transform: translateX(-100%); }
}
<div id="newsTicker">
  <div id="newsText">This is the news text.</div>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.