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

如何实现容器内溢出文字从左到右无限循环滚动的动画效果?

实现方案

以下是修改后可直接运行的完整代码,默认仅当文本长度超出容器时才会启动无限滚动:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
    <div class="auto-scroll">
        <p>
            This text should scroll. Lorem ipsum dolor sit amet consectetur adipisicing elit. Excepturi commodi magni quo officia error ab veniam aspernatur. Quos ducimus, hic, maxime dicta optio quidem
            nostrum sint commodi velit, ut distinctio. And return to beginning.
        </p>
    </div>

    <style>
        .auto-scroll {
            background: black;
            padding: 18px;
            overflow: hidden;
        }
        .auto-scroll p {
            font-family: monospace;
            font-size: 18px;
            color: white;
            margin: 0;
            white-space: nowrap;
        }
        /* 滚动动画类 */
        .auto-scroll p.scroll-animation {
            animation: textScroll 15s linear infinite;
        }
        @keyframes textScroll {
            0% {
                transform: translateX(0);
            }
            100% {
                transform: translateX(-100%);
            }
        }
        /* 隐藏滚动条 */
        .auto-scroll ::-webkit-scrollbar {
            height: 0px;
        }
        .auto-scroll ::-webkit-scrollbar-track {
            background: #000;
        }
        .auto-scroll ::-webkit-scrollbar-thumb {
            background: #fff;
        }
    </style>
    <script>
        const scrollWrapper = document.querySelector('.auto-scroll')
        const scrollContent = scrollWrapper.querySelector('p')
        // 仅当文本宽度超出容器时添加滚动动画
        if (scrollContent.offsetWidth > scrollWrapper.offsetWidth) {
            scrollContent.classList.add('scroll-animation')
        }
    </script>
</body>
</html>

核心修改说明

  • 用CSS transform 实现滚动动画,性能远高于修改left/scrollLeft属性,不会触发页面重排
  • 加了JS宽度判断逻辑,避免短文本不需要滚动时也执行动画
  • 动画默认设置为15秒滚动完成,可自行调整animation属性里的时间值,数值越小滚动速度越快

无缝滚动优化

如果需要避免滚动到文本末尾时出现空白,可以把p标签内的文本复制一份拼接在原有内容后面,同时把动画的最终偏移值改成-50%,就能实现完全无缝的循环滚动效果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 03:48:04