DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS詳解
雙層無縫捲動:讓兩組內容上下接力跑動的跑馬燈
編輯:CSS詳解     

要讓內容連續不斷地往上捲動,單層是不夠的——捲到底就會露出空白。這個範例的解法很聰明:用兩層容器接力,第一層捲出畫面頂端的同時,第二層已經在下方等著補位,如此循環就永遠不會斷。內容還可以直接塞 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>

四個設計要點

  • car_num 同時是步長與速度:每 50 毫秒移 5 像素,就是每分鐘約 6000 像素的節奏。把 car_num 設成 0 等於按下暫停,這正是滑鼠移入時停止捲動的原理。
  • offsetHeight * -1 是換班訊號:當第一層整個移出上方(頂端達到「負的自身高度」),就把它丟回容器底部並換上下一批內容,第二層此時接手。
  • 停頓靠提前 return:抵達交接點時先歸零並排兩個計時器,讓兩層一起休息 8 秒,製造「一輪播完停一下」的節奏。
  • 滑鼠互動:conmouse/cmouseOut 一對函式讓參觀者能把畫面停住看清楚,是很貼心的細節。

今天該怎麼改

這份寫法有三個明顯的時代痕跡。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 排版呈現同樣的內容,效能與維護性都更好。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved