萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

原生 JavaScript 實現文字向上無縫滾動:完整實例與核心邏輯拆解

前言

文字跑馬燈、公告滾動是經典的 UI 需求。本文提供一個**零依賴、相容性極佳**的原生 JS 向上滾動完整實例,包含 HTML 結構、CSS 重置與布局、核心滾動邏輯三大部分,並詳細拆解關鍵技術點:scrollTop 動畫、無縫循環原理、滑鼠暫停/恢復、動態資料渲染。

一、完整可執行代碼(複製即用)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS 文字向上無縫滾動完整實例</title>
<style>
/* === CSS 重置(精簡版) === */
* { margin:0; padding:0; box-sizing:border-box; }
body { font:14px/1.5 "Microsoft YaHei", sans-serif; color:#333; }
ul, ol { list-style:none; }
a { color:#333; text-decoration:none; }
a:hover { color:#c00; text-decoration:underline; }

/* === 滾動容器樣式 === */
#club {
    width: 888px; height: 190px;
    margin: 40px auto;
    border: 1px solid #ddd;
    border-radius: 5px 5px 0 0;
    overflow: hidden; /* 關鍵:裁剪超出內容 */
}
.modle { width: 443px; height: 100%; float: left; border-right: 1px solid #ddd; }
.modle:last-child { border-right: none; float: right; }
.modle_title { height: 29px; line-height: 29px; font-weight: bold; background: #f3f3f3; padding-left: 7px; }
.modle_con { width: 423px; height: 160px; margin: 0 auto; overflow: hidden; position: relative; }
.modle_con ul { position: absolute; left: 0; top: 0; transition: top 0.5s; }
.modle_con li { border-bottom: 1px dotted #ddd; padding: 10px 0; }
.modle_img { width: 50px; height: 79px; float: left; text-align: center; position: relative; }
.modle_img img { margin-top: 14px; max-width: 100%; }
.modle_img i { display: block; width: 15px; height: 17px; background: url(../image/buy.png) no-repeat; position: absolute; top: 10px; left: 60px; }
.modle_text { width: 337px; height: 60px; overflow: hidden; float: right; margin-top: 15px; padding-left: 8px; }
.modle_text p a { color: #005ea7; }
.modle_text div a { color: #999; }
.fn-clear::after { content:""; display:block; clear:both; }
.fn-left { float:left; } .fn-right { float:right; }
</style>
</head>
<body>

<div id="club">
    <div class="modle" id="modle_left">
        <h2 class="modle_title"><span>熱門曬單</span></h2>
        <div class="modle_con">
            <ul id="scrollList1"></ul>
        </div>
    </div>
    <div class="modle modle_right">
        <h2 class="modle_title"><span>最新曬單</span></h2>
        <div class="modle_con">
            <ul id="scrollList2"></ul>
        </div>
    </div>
</div>

<script>
// === 核心滾動類 ===
class TextScroller {
    constructor(ulId, data, options = {}) {
        this.ul = document.getElementById(ulId);
        this.data = data; // [{img, title, desc, url}, ...]
        this.rowHeight = options.rowHeight || 80; // 每行高度(含邊框)
        this.delay = options.delay || 3000;       // 停留毫秒
        this.speed = options.speed || 500;        // 滾動動畫毫秒
        this.timer = null;
        this.index = 0;
        this.init();
    }

    init() {
        this.render();
        this.cloneFirst(); // 關鍵:複製第一項到末尾實現無縫
        this.bindEvents();
        this.autoPlay();
    }

    render() {
        this.ul.innerHTML = this.data.map(item => `
            <li class="fn-clear">
                <div class="modle_img fn-left">
                    <a href="${item.url}"><img src="${item.img}" alt=""></a>
                    <i></i>
                </div>
                <div class="modle_text fn-right">
                    <p><a href="${item.url}">${item.title}</a></p>
                    <div><a href="${item.url}">${item.desc}</a></div>
                </div>
            </li>
        `).join('');
    }

    cloneFirst() {
        if (this.data.length > 0) {
            const firstLi = this.ul.firstElementChild.cloneNode(true);
            this.ul.appendChild(firstLi);
        }
    }

    bindEvents() {
        this.ul.addEventListener('mouseenter', () => this.stop());
        this.ul.addEventListener('mouseleave', () => this.autoPlay());
    }

    autoPlay() {
        this.stop();
        this.timer = setInterval(() => this.scrollNext(), this.delay + this.speed);
    }

    stop() { clearInterval(this.timer); }

    scrollNext() {
        this.index++;
        const targetTop = -this.index * this.rowHeight;
        this.ul.style.transition = `top ${this.speed}ms ease`;
        this.ul.style.top = targetTop + 'px';

        // 無縫重置:動畫結束後瞬間跳回 0
        if (this.index === this.data.length) {
            setTimeout(() => {
                this.ul.style.transition = 'none';
                this.ul.style.top = '0';
                this.index = 0;
            }, this.speed);
        }
    }
}

// === 模擬資料 ===
const data1 = [
    { img: 'https://picsum.photos/seed/1/50/79', title: '很不錯的一款電熱壺喲', desc: '速度很快。信號很好,而且設置方便。最關鍵的是,能看到流量使用了多', url: '#' },
    { img: 'https://picsum.photos/seed/2/50/79', title: '第二條曬單標題較長一些', desc: '這是描述文字內容描述文字內容描述文字內容', url: '#' },
    { img: 'https://picsum.photos/seed/3/50/79', title: '第三條曬單', desc: '另一段描述文字', url: '#' },
    { img: 'https://picsum.photos/seed/4/50/79', title: '第四條曬單', desc: '更多描述內容', url: '#' }
];
const data2 = [
    { img: 'https://picsum.photos/seed/5/50/79', title: '最新曬單一', desc: '最新描述一', url: '#' },
    { img: 'https://picsum.photos/seed/6/50/79', title: '最新曬單二', desc: '最新描述二', url: '#' },
    { img: 'https://picsum.photos/seed/7/50/79', title: '最新曬單三', desc: '最新描述三', url: '#' }
];

// === 初始化 ===
new TextScroller('scrollList1', data1, { rowHeight: 100, delay: 2500 });
new TextScroller('scrollList2', data2, { rowHeight: 100, delay: 3000 });
</script>
</body>
</html>

二、核心技術點拆解

1. 無縫循環原理:Clone + 瞬間重置

  • 渲染 N 條資料 → ul 高度 = N × rowHeight
  • 複製第 1 條 li 追加到末尾 → 視覺上變成 N+1 條
  • 滾動至第 N 條(索引 N-1 → N)時,畫面顯示的是複製項(與第 1 項相同)
  • 動畫結束瞬間:transition: none + top: 0 + index = 0,使用者無感知

2. CSS 關鍵點

  • 容器 overflow: hidden + 固定高度
  • ul { position: absolute; top: 0; } 透過改變 top 實現位移
  • transition 控制滾動平滑度,重置時移除 transition 避免倒退動畫

3. 滑鼠互動體驗

mouseenter 清除定時器暫停,mouseleave 重新啟動,符合使用者直覺操作。

4. ES6 Class 封裝優勢

  • 多實例互不干擾(頁面可放多個滾動區塊)
  • 配置參數化(行高、延遲、速度)
  • 資料驅動視圖,支援動態 ajax 獲取後 scroller.data = newData; scroller.render();

三、進階擴展建議

  • 向左/向右滾動:改操作 left、寬度計算、白 nowrap 白名單
  • 無限載入:滾動到底部時 fetch 新資料 append 至 ul(需調整 clone 邏輯)
  • 觸控支援:添加 touchstart/move/end 實現手機拖拽滾動
  • 無障礙:添加 aria-live="polite"、鍵盤焦點控制

結語

這個不到 100 行的原生 JS 類,展現了「資料驅動 + CSS 動畫 + 狀態機」的現代前端思想。相比老舊的 setInterval + scrollTop++ 像素級位移,transition 方案效能更高、程式碼更清晰、易於維護擴展。直接複製到專案即可使用,或作為學習原生動畫邏輯的範本。

copyright © 萬盛學電腦網 all rights reserved