要做一個向上捲動的文字公告欄,核心思路是:先把內容複製一份,讓總高度超過容器,再定時微調 scrollTop;滾到一半時瞬間歸零,視覺上就形成無縫循環。
<div id="marqueey">
<table width="476" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="22" align="center">
<img src="images/items.gif" width="16" height="14">
</td>
<td height="19" width="450">
<a href="" class="tList" target="">文字向上滾動代碼</a>
</td>
</tr>
<tr>
<td colspan="2" background="images/line.gif" height="3"></td>
</tr>
</table>
</div>
<script>
var marqueeyHeight = 140; // 定義容器高度
var stopscroll = false;
// 設定容器的溢出與換行行為
with (marqueey) {
style.width = 0;
style.height = marqueeyHeight;
style.overflowX = "visible";
style.overflowY = "hidden";
noWrap = true;
onmouseover = new Function("stopscroll = true");
onmouseout = new Function("stopscroll = false");
}
document.write('<div id="templayer" style="position:absolute;z-index:1;visibility:hidden"></div>');
var preTop = 0, currentTop = 0;
function init() {
templayer.innerHTML = "";
// 不斷複製內容,直到暫存層高度超過容器高度
while (templayer.offsetHeight < marqueeyHeight) {
templayer.innerHTML += marqueey.innerHTML;
}
// 把暫存內容放兩份,形成循環
marqueey.innerHTML = templayer.innerHTML + templayer.innerHTML;
setInterval("scrollUp()", 40); // 數值越大滾得越慢
}
document.body.onload = init;
function scrollUp() {
if (stopscroll == true) return;
preTop = marqueey.scrollTop;
marqueey.scrollTop += 1;
// 若已到不了更下面,代表滾完一份,歸零重新開始
if (preTop == marqueey.scrollTop) {
marqueey.scrollTop = templayer.offsetHeight - marqueeyHeight;
marqueey.scrollTop += 1;
}
}
</script>
為什麼要複製兩份? 內容滾到看不見時,如果只有一份,後面就是空白;放兩份之後,當第一份滾出視線,第二份正好接上,歸零的瞬間視覺上毫無斷點。
怎麼判斷滾到底? 程式的做法很聰明——比較加一之前與之後的 scrollTop。如果沒變,代表已經沒有更多內容可滾,這就是歸零的時機。
滑鼠移入暫停。 用 onmouseover/onmouseout 控制一個旗標,讓使用者能把游標停在感興趣的文字上閱讀。
範例中的 with 陳述式在嚴格模式下被禁用,document.write 也會阻塞解析,setInterval("scrollUp()", 40) 這種字串形式的計時器相當於隱性的 eval。這些都是應該避免的舊寫法。
今天要實作同樣的效果,用 CSS 動畫會流暢得多,也能交給 GPU 合成:
.marquee {
height: 140px;
overflow: hidden;
}
.marquee-inner {
animation: scrollUp 10s linear infinite;
}
.marquee:hover .marquee-inner {
animation-play-state: paused; /* 滑鼠移入暫停 */
}
@keyframes scrollUp {
from { transform: translateY(0); }
to { transform: translateY(-50%); }
}
另外,自動捲動的內容對有注意力障礙或前庭功能敏感的使用者可能造成困擾,建議尊重系統的 prefers-reduced-motion 設定,並確保隨時可以暫停。