要讓內容連續不斷地往上捲動,單層是不夠的——捲到底就會露出空白。這個範例的解法很聰明:用兩層容器接力,第一層捲出畫面頂端的同時,第二層已經在下方等著補位,如此循環就永遠不會斷。內容還可以直接塞 iframe,當成廣告輪播使用。
<script>
var dde_para = new Array();
var dde_url = document.location.href;
var dde_pp = dde_url.split("#")[1]; // 可從網址 # 後帶入參數
var scrollwidth = 740; // 捲動區寬
var scrollheight = 175; // 捲動區高
var car_num = 5; // 每次移動的像素,也是速度
var i = 1;
var pausebetweenimages = 1000 * 8; // 停頓 8 秒
var slideimages = new Array();
slideimages[0] =
"<iframe border=0 vspace=0 hspace=0 bgcolor=#888888 " +
"marginwidth=0 marginheight=0 framespacing=0 frameborder=0 " +
"scrolling=no width=" + scrollwidth + " height=" + scrollheight +
" src='iframe1.htm'></iframe>";
slideimages[1] =
"<iframe border=0 vspace=0 hspace=0 bgcolor=#888888 " +
"marginwidth=0 marginheight=0 framespacing=0 frameborder=0 " +
"scrolling=no width=" + scrollwidth + " height=" + scrollheight +
" src='iframe2.htm'></iframe>";
function move1(whichdiv) {
var tdiv = eval(whichdiv);
if (tdiv.style.pixelTop > 0 && tdiv.style.pixelTop <= car_num) {
tdiv.style.pixelTop = 0;
setTimeout("move1(tdiv)", pausebetweenimages);
setTimeout("move2(second2)", pausebetweenimages);
return;
}
if (tdiv.style.pixelTop >= tdiv.offsetHeight * -1) {
tdiv.style.pixelTop -= car_num;
setTimeout("move1(tdiv)", 50);
} else {
tdiv.style.pixelTop = scrollheight;
tdiv.innerHTML = slideimages[0];
if (i == slideimages.length - 1) i = 0; else i++;
}
}
function move2(whichdiv) { /* 與 move1 相同,換成第二層與 slideimages[1] */ }
function conmouse() { car_num = 0; } // 滑鼠移入 → 暫停
function cmouseOut() { car_num = 5; } // 滑鼠移出 → 恢復
function startscroll() {
if (document.all) {
move1(first2);
second2.style.top = scrollheight;
}
}
</script>
這份寫法有三個明顯的時代痕跡。document.all 與 pixelTop 都是 IE 專屬;eval(whichdiv) 只是為了把字串變成元素,現在傳元素物件進函式即可;而 <ilayer>/<layer> 更是早已淘汰的 Netscape 標籤。
現代的等效做法是 CSS 動畫:把內容複製一份接在後面,讓整個容器用 @keyframes 從 translateY(0) 移到 translateY(-50%),動畫結束剛好接回起點,無縫循環不需要任何 JavaScript:
<style>
.marquee { height:175px; overflow:hidden; }
.marquee ul { animation: scrollUp 20s linear infinite; }
.marquee:hover ul { animation-play-state: paused; }
@keyframes scrollUp {
from { transform: translateY(0); }
to { transform: translateY(-50%); }
}
</style>
用 :hover 暫停也比改變數乾淨。至於原本的 iframe 內嵌,今天更建議用純 HTML 結構搭配 flex 排版呈現同樣的內容,效能與維護性都更好。