PAYATHON 2026

如何在 JavaScript 中让多行 marquee 文本分别独立动画?

数据小陈

结论

多行 marquee 想各自独立动画,得把每行的 pos、dir、速度以及可移动边界从全局变量拆成实例状态,光改 CSS 不够。原来的代码里 pos 和 dir 只有一个,所有行共用同一个位置和方向,所以最长行碰到边界并反转时,其他行也会跟着反转。

原因

原代码在 for 循环里一遍遍执行:

pos = pos + dir;
if (pos >= containerWidth - textWidth) {
  dir = -1;
} else if (pos <= 0) {
  dir = 1;
}

这段逻辑依赖 containerWidth 和 textWidth,但 pos、dir 没有按行隔离。循环到第二行时,pos 已经带着第一行的移动量;第二行的边界判断还会继续改同一个 dir。结果就是每行的当前位置和方向互相影响。

边界范围也要留意:containerWidth - textWidth 可能是负数。文本比容器宽时,可移动范围应是 containerWidth - textWidth 到 0,不能按 0 到 containerWidth - textWidth 来算。用 min 和 max 记录每行的上下界,文本较宽时就不容易在 0 附近抖动。

解决步骤

  1. 用 querySelectorAll 拿到所有容器,再给每个容器找到对应的 .marquee_text。
  2. 每个 marquee 建一个独立对象,保存 pos、dir、speed、min、max。
  3. 按每行自己的容器宽度和文本宽度算出 min 和 max。
  4. 用一个 requestAnimationFrame 循环遍历所有实例,分别更新每个实例的 pos 和 dir,再写入自己的 left。
  5. 在 resize 时重新测量边界,窗口尺寸变了,动画范围也不会出错。

代码示例

HTML:

<div class='marquee_container'>
  <span class='marquee_text'>This is a line of marquee.</span>
</div>

<p>This is just normal text</p>

<div class='marquee_container'>
  <span class='marquee_text'>This is another and longer line of marquee</span>
</div>

CSS:

.marquee_container {
  overflow: hidden;
}

.marquee_text {
  position: relative;
  left: 0;
  display: inline-block;
  white-space: nowrap;
  will-change: left;
}

JavaScript:

const marquees = [...document.querySelectorAll('.marquee_container')].map((container) => {
  const text = container.querySelector('.marquee_text');
  return {
    container,
    text,
    pos: 0,
    dir: 1,
    speed: 1,
    min: 0,
    max: 0
  };
});

function updateBounds(item) {
  const diff = item.container.clientWidth - item.text.offsetWidth;
  item.min = Math.min(0, diff);
  item.max = Math.max(0, diff);

  // 防止窗口变化后当前位置越界
  item.pos = Math.min(item.max, Math.max(item.min, item.pos));
}

function measureAll() {
  marquees.forEach(updateBounds);
}

measureAll();
window.addEventListener('resize', measureAll);

function animate() {
  marquees.forEach((item) => {
    if (item.max === item.min) {
      item.text.style.left = '0px';
      return;
    }

    item.pos += item.dir * item.speed;

    if (item.pos >= item.max) {
      item.pos = item.max;
      item.dir = -1;
    } else if (item.pos <= item.min) {
      item.pos = item.min;
      item.dir = 1;
    }

    item.text.style.left = item.pos + 'px';
  });

  requestAnimationFrame(animate);
}

requestAnimationFrame(animate);

注意事项

  • pos 和 dir 要放在每个 marquee 实例里,不能挂到全局作用域让循环共用。
  • 文本比容器宽时,containerWidth - textWidth 是负数,边界要用 min/max 处理,否则容易抖动或反弹位置不对。
  • offsetWidth、clientWidth 会触发布局计算,别每一帧都读。示例只在初始化和 resize 时测量;如果文本内容会动态变化,内容变化后再调用 measureAll()。
  • 上面的示例是左右弹跳效果。想要传统 marquee 那种单向循环滚动,需要用取模或重置位置来实现,不能直接套用弹跳判断。
  • 原生 <marquee> 已废弃且非标准,新项目不建议依赖它;对可访问性要求高的场景,优先考虑 CSS 动画或更可控的滚动组件。 备注:内容仅供参考。