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

CSS无缝无限滚动文字跑马灯的宽度问题解决问询

实现无缝滚动文字(Marquee)的解决方案

你的核心问题是动画位移范围与文本元素宽度不匹配,导致文本移出容器左侧后出现长时间空白间隔。要实现无缝滚动,需让文本滚动的终点恰好衔接下一次循环的起点,同时调整文本元素宽度与动画逻辑的匹配性。

调整后的完整代码实现

HTML 部分

保留原有结构,确保文本单行无换行:

<div class="d-none d-lg-flex row topmarquee mt-4">
  <div class="marquee">
    <p id="marqueeText" class="marqueeText mb-0">
      This is a test website
    </p>
  </div>
</div>

CSS 部分

移除文本元素的强制宽度,修改动画关键帧的位移范围,确保循环衔接:

@keyframes marquee-animation {
  from {
    /* 从容器右侧外部位置开始 */
    transform: translate3d(100%, 0, 0);
  }
  to {
    /* 滚动至文本完全移出容器左侧的位置,刚好衔接下一次循环起点 */
    transform: translate3d(calc(-100% - 100%), 0, 0);
  }
}

.topmarquee {
  width: 100%;
  border: 1px solid #000;
}

.topmarquee .marquee {
  width: calc(100% - 200px);
  position: relative;
  overflow: hidden;
  height: 31px;
}

.topmarquee .marquee #marqueeText {
  display: block;
  position: absolute;
  top: 0;
  right: 0;
  margin: 0;
  white-space: nowrap;
  animation-name: marquee-animation;
  animation-iteration-count: infinite;
  animation-timing-function: linear;
  line-height: 31px;
  /* 移除width:100%,让宽度由文本内容自动决定 */
}

JavaScript 部分

动态计算容器与文本宽度,确保滚动速度一致:

const timePerPixel = 5; // 每像素滚动耗时(毫秒)
const marqueeContainer = document.querySelector('.marquee');
const text = document.getElementById('marqueeText');

// 获取容器和文本的实际渲染宽度
const containerWidth = marqueeContainer.offsetWidth;
const textWidth = text.offsetWidth;

// 总滚动距离:文本从右侧进入到完全移出左侧的总长度
const totalDistance = containerWidth + textWidth;
// 计算动画总时长
const duration = timePerPixel * totalDistance;

text.style.animationDuration = `${duration}ms`;

关键逻辑说明

  1. 移除强制宽度:去掉#marqueeText的width:100%,避免文本元素被拉伸至容器宽度,减少不必要的滚动距离。
  2. 精准动画位移:动画终点设置为calc(-100% - 100%),其中第一个-100%对应文本自身宽度的位移,第二个-100%对应容器宽度的位移,确保文本完全移出左侧时,下一次循环的起点(容器右侧外部)会立即显示文本,实现无缝衔接。
  3. 动态适配尺寸:通过offsetWidth获取容器实际宽度(而非硬编码数值),适配不同屏幕尺寸,保证滚动速度始终一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 02:52:44