垂直滾動公告常用於側邊欄、通知列表。本文提供基於 jQuery 的完整實現,包含動畫平滑過渡、鼠標懸停暫停、自動恢復等核心交互。
<div id="notice">
<p>第一條公告內容</p>
<p>第二條公告內容</p>
<p>第三條公告內容</p>
</div>
#notice { height: 35px; overflow: hidden; position: relative; }
#notice p { height: 35px; line-height: 35px; margin: 0; }
var rollTimer;
function textRoll() {
// 取最後一個 p,設置初始狀態(高度 0、透明),移至首位,然後動畫展開
$('#notice p:last')
.css({height: 0, opacity: 0})
.prependTo('#notice')
.animate({height: '35px', opacity: 1}, 'slow', function() {
$(this).removeAttr('style'); // 動畫完成清除內聯樣式,恢復 CSS 類控制
});
}
$(function() {
// 啟動定時器(4 秒滾動一次)
rollTimer = setInterval(textRoll, 4000);
// 鼠標進入暫停,離開恢復
$('#notice p').hover(
function() { clearInterval(rollTimer); },
function() { rollTimer = setInterval(textRoll, 4000); }
);
});
height:0 → 35px + opacity:0 → 1 創造淡入推擠感,優於單純 margin-top 位移。p 上,實際上建議綁定在 #notice 容器上,避免動畫過程中元素位置變化導致事件誤觸發。update(dataArray) 方法重新渲染列表。$.fn.vMarquee = function(options){...} 支持多實例、配置項解耦。掌握此模式,快速構建穩定、可維護的垂直滾動公告組件。