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

如何将jQuery实现的跑马灯animate动画转换为纯JavaScript代码

纯JavaScript实现无依赖跑马灯

实现逻辑说明

原jQuery版本跑马灯的核心运行逻辑为:页面加载完成后获取滚动文本元素、计算元素自身宽度与父容器宽度,将元素初始定位在父容器右侧外部,再通过线性动画将元素移动到父容器左侧外部,动画结束后循环触发下一次滚动。
以下实现完全移除jQuery依赖,采用原生JS+CSS过渡实现同等效果,性能更优,加载开销更小。

完整可运行代码

<!-- 必要样式 -->
<style>
.scroll {
  position: relative;
  overflow: hidden;
  width: 100%;
  height: 24px;
  line-height: 24px;
}
.scrollingtext {
  position: absolute;
  white-space: nowrap;
}
</style>

<!-- 页面结构和原版本完全一致 -->
<div class="scroll">
  <div class="scrollingtext">Flash message without marquee tag using javascript!</div>
</div>

<!-- 纯JS逻辑 -->
<script>
document.addEventListener('DOMContentLoaded', function () {
  const scrollText = document.querySelector('.scrollingtext')
  const parentEl = scrollText.parentElement
  const scrollDuration = 20000 // 滚动总时长,单位毫秒,和原版本20s保持一致

  function startMarquee() {
    const textWidth = scrollText.offsetWidth
    const parentWidth = parentEl.offsetWidth

    // 重置初始位置,关闭过渡避免重置过程出现动画
    scrollText.style.transition = 'none'
    scrollText.style.right = `-${textWidth}px`

    // 强制浏览器重绘,确保初始位置生效
    void scrollText.offsetWidth

    // 开启过渡,启动滚动动画
    scrollText.style.transition = `right ${scrollDuration}ms linear`
    scrollText.style.right = `${parentWidth}px`
  }

  // 动画结束后自动触发下一轮滚动
  scrollText.addEventListener('transitionend', startMarquee)
  // 启动首次滚动
  startMarquee()
})
</script>

参数调整说明

  • 如需调整滚动速度,修改scrollDuration变量的数值即可,数值越大滚动速度越慢
  • 父容器scroll的宽高样式可根据业务需求自由调整,不影响滚动逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 05:06:01