首頁的新聞快訊區常需要這種效果:文字一行一行往上捲,滑鼠移入時暫停,移開後繼續。實作關鍵是「複製一份內容」與「定時器控制」。
<div id="title" style="width:100%;height:40px;">看看間斷滾動文字</div>
<div id="content" class="infocontent">
<div id="top" class="infolist">
<ul>
<li>第一條新聞標題</li>
<li>第二條新聞標題</li>
<li>第三條新聞標題</li>
<li>第四條新聞標題</li>
</ul>
</div>
<div id="bottom" class="infolist"></div>
</div>
<div id="foot"></div>.infolist{width:400px;margin:0;}
.infolist ul{margin:0;padding:0;}
.infolist ul li{list-style:none;height:26px;line-height:26px;}
.infocontent{width:400px;height:26px;overflow:hidden;border:1px solid #666666;}可視高度固定 26px,正好等於一行的高度,多餘的內容被隱藏起來。
var interval = 1000; // 兩次滾動之間的間隔(毫秒)
var stepsize = 26; // 每次滾動的距離,必須是行高的倍數,否則會斷行
var objInterval = null;
$(document).ready(function(){
// 用上方的內容填滿下方,形成無縫接續
$("#bottom").html($("#top").html());
// 滑鼠移入暫停、移出恢復
$("#content").bind("mouseover", function(){ StopScroll(); });
$("#content").bind("mouseout", function(){ StartScroll(); });
StartScroll();
});
function StartScroll(){
objInterval = setInterval("verticalloop()", interval);
}
function StopScroll(){
window.clearInterval(objInterval);
}
function verticalloop(){
// 若上方內容已全部移出可視區,則回到起點重新開始
if ($("#content").scrollTop() >= $("#top").outerHeight()) {
$("#content").scrollTop($("#content").scrollTop() - $("#top").outerHeight());
}
// 用 animate 產生平滑的捲動動畫
$("#content").animate(
{ "scrollTop": $("#content").scrollTop() + stepsize + "px" },
600,
function(){
// 除錯用:可顯示目前的 scrollTop,正式環境請移除
// $("#foot").html("scrollTop:" + $("#content").scrollTop());
}
);
}#bottom 複製一份清單是為了讓內容銜接時不出現空白;stepsize 一定要對齊行高,否則捲動會切到半行文字,看起來像斷行;而滑鼠事件綁在外層容器上,讓使用者有機會停下來看清楚感興趣的內容。