公告欄左右滾動是經典 UI 需求。本文拆解原生 JS 實現核心邏輯,無依賴、可控性強、易於封裝為 jQuery 插件或 Web Component。
<div id="scrollText">
<div class="content">這裡是滾動的公告內容...</div>
</div>
#scrollText {
width: 400px; margin: 0 auto; overflow: hidden; position: relative;
}
.content { position: absolute; white-space: nowrap; }
var ScrollTime;
function ScrollAutoPlay(contID, scrolldir, showWidth, textWidth, step) {
var $el = $('#' + contID).children().first(); // 獲取 .content
var currPos = parseInt($el.css('margin-left')) || 0;
if (scrolldir === 'left') {
// 向左滾動:內容向左移出,當完全移出視口寬度時重置到右側
if (currPos < 0 && Math.abs(currPos) > textWidth) {
$el.css('margin-left', showWidth);
} else {
$el.css('margin-left', currPos - step);
}
} else {
// 向右滾動:內容向右移出,當超出視口右側時重置到左側負寬度
if (currPos > showWidth) {
$el.css('margin-left', -textWidth);
} else {
$el.css('margin-left', currPos + step); // 注意:原碼此處為 -step,向右應為 +step
}
}
}
// 啟動
ScrollTime = setInterval(function() {
ScrollAutoPlay('scrollText', 'left', 400, $('.content').outerWidth(), 2);
}, 30); // 30ms/幀 ≈ 33fps
// 鼠標懸停暫停
$('#scrollText').hover(
() => clearInterval(ScrollTime),
() => ScrollTime = setInterval(...)
);
| 參數 | 含義 |
|---|---|
| contID | 容器 ID |
| scrolldir | 'left' 或 'right' |
| showWidth | 可視區寬度(容器寬度) |
| textWidth | 內容實際寬度(需動態獲取) |
| step | 每幀移動像素,控制速度 |
requestAnimationFrame 替代 setInterval,幀率更穩、省電。textWidth 並重置位置。$.fn.marquee(options) 插件,暴露 direction/speed/pauseOnHover 等配置。理解核心邏輯,即可靈活定製符合業務需求的滾動公告組件。