垂直列表按指定行數分組,每組獨立向上滾動一行,滾動完成後將第一行移至末尾,形成無縫循環。多組錯開時間啟動,形成「百葉窗」視覺效果。
overflow: hidden。scrollTop 漸增 → 達到行高 → 移動首行至尾部 → 重置 scrollTop。rt 毫秒啟動,整體循環間隔 t 毫秒。(function ($) {
$.fn.verticalRoller = function (options) {
const opts = $.extend({
lineCount: 4, // 可視行數
interval: 5000, // 整體循環間隔
rollDuration: 500, // 單行滾動耗時
itemTag: 'li', // 子元素標籤
wrapTag: 'ul' // 分組包裹標籤
}, options);
return this.each(function () {
const $container = $(this);
const $items = $container.children(opts.itemTag);
if ($items.length <= opts.lineCount) return; // 不足一屏不滾動
// 1. 分組包裹
const groupCount = Math.ceil($items.length / opts.lineCount);
const $groups = [];
for (let i = 0; i < groupCount; i++) {
const $wrap = $('<' + opts.wrapTag + '>').css({
overflow: 'hidden',
height: $items.outerHeight() * opts.lineCount,
'margin-bottom': '15px'
});
$items.slice(i * opts.lineCount, (i + 1) * opts.lineCount).wrapAll($wrap);
$groups.push($wrap);
}
const lineHeight = $items.outerHeight();
const frames = Math.ceil(opts.rollDuration / 16); // 約 60fps
const step = lineHeight / frames;
// 2. 單組滾動函式
function rollGroup($group) {
let frame = 0;
const timer = setInterval(() => {
frame++;
$group.scrollTop($group.scrollTop() + step);
if (frame >= frames) {
clearInterval(timer);
// 修正誤差並移動首行到尾部
$group.scrollTop($group.scrollTop() + lineHeight - step * frames);
const $first = $group.children(opts.itemTag).first();
$group.append($first);
$group.scrollTop(-lineHeight); // 瞬間回撥,形成無縫銜接
}
}, 16);
}
// 3. 錯開啟動所有組
function startCycle() {
$groups.forEach(($g, i) => {
setTimeout(() => rollGroup($g), i * opts.rollDuration);
});
}
// 4. 總循環定時器
setInterval(startCycle, opts.interval);
startCycle(); // 立即執行第一輪
});
};
})(jQuery);
// 使用範例
$('#news-list').verticalRoller({
lineCount: 4,
interval: 5000,
rollDuration: 500
});
<div id="news-list" class="dynamic">
<li><a href="#">標題 1</a></li>
<li><a href="#">標題 2</a></li>
<li><a href="#">標題 3</a></li>
<li><a href="#">標題 4</a></li>
<li><a href="#">標題 5</a></li>
<li><a href="#">標題 6</a></li>
<!-- 更多 li -->
</div>
#news-list { width: 300px; }
#news-list li { height: 30px; line-height: 30px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
#news-list ul { overflow: hidden; } /* 插件自動添加 */
mouseenter/mouseleave 清除/恢復總定時器。transform: translateY() + transition 替代 scrollTop,啟用 GPU 加速。getBoundingClientRect().height 動態計算。destroy() 方法的物件,清理定時器與 DOM 綁定。