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

如何让JavaScript实现的Marquee组件从左到右滚动并正常循环?

问题:Marquee左到右滚动无法循环的解决办法?

我基于一段代码制作Marquee滚动效果,希望将其从右到左滚动改为从左到右。移除了代码第11行-${i}px中的负号实现了方向反转,但现在文本无法像原代码那样循环滚动,只会滑出屏幕。

修改后的JavaScript代码

function MarqueeOne(selector, speed) {
  const parentSelector = document.querySelector(selector);
  const clone = parentSelector.innerHTML;
  const firstElement = parentSelector.children[0];
  let i = 0;
  console.log(firstElement);
  parentSelector.insertAdjacentHTML('beforeend', clone);
  parentSelector.insertAdjacentHTML('beforeend', clone);

  setInterval(function () {
    firstElement.style.marginLeft = `${i}px`;
    if (i > firstElement.clientWidth) {
      i = 0;
    }
    i = i + speed;
  }, 0);
}

CSS代码

.marquee-one {
  overflow: hidden;
  border-top: 1px solid #000;
  border-bottom: 1px solid #000;
  display: flex;
  color: white;
}

.marquee-one h1{
  font-size: 5em;
  white-space: nowrap;
  text-transform: uppercase;
  color: white;
}

解决方案

问题出在滚动的判断条件和重置逻辑上:原代码是向左滚动,当元素的marginLeft负到自身宽度时重置为0;而向右滚动时,需要调整判断时机和重置值,让克隆元素能无缝衔接。

修改后的JavaScript代码如下:

function MarqueeOne(selector, speed) {
  const parentSelector = document.querySelector(selector);
  const clone = parentSelector.innerHTML;
  const firstElement = parentSelector.children[0];
  let i = 0;
  
  parentSelector.insertAdjacentHTML('beforeend', clone);
  parentSelector.insertAdjacentHTML('beforeend', clone);

  setInterval(function () {
    firstElement.style.marginLeft = `${i}px`;
    // 当第一个元素完全移出父容器右侧时,重置位置
    if (i > parentSelector.clientWidth) {
      // 把第一个元素移到左侧外部,让克隆元素衔接上来
      i = -firstElement.clientWidth;
    }
    i = i + speed;
  }, 0);
}

关键修改点:

  1. 判断条件:将i > firstElement.clientWidth改为i > parentSelector.clientWidth,判断时机是第一个元素完全移出父容器的可视区域。
  2. 重置值:将i = 0改为i = -firstElement.clientWidth,此时第一个元素会瞬间移动到父容器左侧外面,第二个克隆元素刚好处于父容器的起始位置,继续向右滚动,实现无缝循环。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 08:42:05