You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让媒体播放器的滚动字幕动画中止时完成当前周期再停止?

问题

我正在开发一款媒体播放器,使用JavaScript和CSS实现了歌曲元信息的跑马灯式滚动效果,仅在曲目播放时启用。通过点击播放/暂停按钮,用JS添加或移除animation类。想请教:若在动画中途移除该类,能否让动画完成当前周期后再停止?


解决方案

默认情况下,直接移除scrolling类会立刻终止动画,元素瞬间回到初始位置。要实现动画完成当前周期后再停止,可以通过监听动画循环事件结合状态标记来实现,具体步骤如下:

核心思路

  1. 用变量标记是否需要停止动画,点击暂停时不直接移除类,而是设置这个标记
  2. 监听动画的animationiteration事件(该事件在每一次完整动画循环结束时触发)
  3. 当事件触发时,检查标记状态,若需要停止则移除动画类

修改后的代码

JavaScript

var MetaScroll = document.getElementById("MetaScroll");
var PlayButton = document.getElementById("PlayButton");
var shouldStopScroll = false; // 标记是否需要停止滚动

// 监听动画完成一次循环的事件
MetaScroll.addEventListener('animationiteration', function() {
  if (shouldStopScroll) {
    MetaScroll.classList.remove('scrolling');
    shouldStopScroll = false; // 重置标记
  }
});

function playPause() {
  if (MetaScroll.classList.contains('scrolling')) {
    // 当前正在滚动,标记需要停止,等待当前周期结束
    shouldStopScroll = true;
  } else {
    // 当前未滚动,直接启动动画
    MetaScroll.classList.add('scrolling');
    shouldStopScroll = false;
  }
  PlayButton.classList.toggle('fa-play');
  PlayButton.classList.toggle('fa-pause');
}

CSS(保留原代码)

body {
  background: black;
}

.albumArt {
  width: 200px;
  height: 200px;
  border: 3px solid #212121;
  display: flex;
  flex-direction: column-reverse;
}

.metaContainer {
  height: 25%;
  overflow: hidden;
  background-color: white;
}

.meta {
  white-space: nowrap;
  height: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
}

.meta p {
  font-family: Courier, monospace;
  font-size: 20px;
  margin: 0;
  color: black;
}

.scrolling {
  transform: translateX(0);
  animation: b-text-scroll 5s linear infinite;
}

@keyframes b-text-scroll {
  0% {
    transform: translate3d(0, 0, 0);
  }
  20% {
    transform: translate3d(0, 0, 0);
  }
  100% {
    transform: translate3d(-100%, 0, 0);
  }
}

.pIcons {
  font-size: 20px;
  color: white;
  background-color: transparent;
  border: none;
}

HTML(保留原代码)

<script src="https://kit.fontawesome.com/1706aa300d.js" crossorigin="anonymous"></script>

<body>
  <div class="albumArt">
    <div class="metaContainer">
      <div id="MetaScroll" class="meta">
        <p>&nbsp; The Absense of a Title - A Deadly Lack of Artist</p>
        <p>&nbsp; The Absense of a Title - A Deadly Lack of Artist</p>
      </div>
    </div>
  </div>
  <button class="pIcons" onclick="playPause()">
    <i id="PlayButton" class="fa-solid fa-play"></i>
  </button>
</body>

逻辑说明

  • 点击暂停按钮时,不会立刻移除scrolling类,而是将shouldStopScroll设为true,让动画继续运行到当前周期结束
  • 当动画完成一次完整循环(5秒周期结束),animationiteration事件触发,此时检查shouldStopScroll状态,为true则移除动画类,停止滚动
  • 点击播放按钮时,直接添加scrolling类并重置标记,确保动画正常启动

内容的提问来源于stack exchange,提问作者RP5715

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 02:13:24