DIV CSS 佈局教程網

文字向左滾動:用 JS 手寫一個跑馬燈效果
編輯:關於JavaScript     

在空間有限的側欄裡想塞進一大段公告,跑馬燈式的捲動是個經典解法。這份範例不依賴任何套件,靠 setTimeout 與 marginLeft 就能讓文字由右往左持續流動。

CSS:先裁出可視範圍

#infozone{
  font-size:12px;
  color:#aa6;
  overflow:hidden;   /* 關鍵:超出部分不顯示 */
  width:100px;
  height:20px;
}
#infozone div{
  height:20px;
  line-height:20px;
  white-space:nowrap;  /* 不換行,才能橫向捲動 */
  overflow:hidden;
}

white-space:nowrap 與外層的 overflow:hidden 是一組必搭的組合:前者讓文字保持單行,後者把移出視窗的部分藏起來。

JS:橫向捲動函式

var tc;
window.onload = function(){
  var o = document.getElementById('infozone');
  hscroll(o);
  // 每 10 秒重置一次,讓動畫可以無限循環
  window.setInterval(function(){
    window.clearTimeout(tc);
    o.firstChild.style.marginLeft = '0px';
    scrollup(o, 20, 0);
  }, 10000);
}

function hscroll(o){
  var w1 = o.firstChild.offsetWidth,   // 文字實際寬度
      w2 = o.offsetWidth;              // 容器寬度
  if(w1 <= w2) return;                 // 文字不夠長就不必捲
  tc = window.setTimeout(function(){
    hs(o, w1 - w2, 0, w1 - w2);
  }, 3500);                            // 停留 3.5 秒後才開始動
}

function hs(o, d, c, p){
  c++;
  var t = (c > 0 ? -c : c);
  o.firstChild.style.marginLeft = t + 'px';
  if(c == d){
    if(d == 0){
      tc = window.setTimeout(function(){ hs(o, p, 0, p); }, 2500);
    }else{
      tc = window.setTimeout(function(){ hs(o, 0, -p, p); }, 3500);
    }
  }else{
    tc = window.setTimeout(function(){ hs(o, d, c, p); }, 5);
  }
}

原理並不複雜:w1 - w2 就是「文字尾巴剛好移出視窗」所需的位移量,hs() 每 5 毫秒把 marginLeft 遞減 1px,走到終點後再回到起點,形成循環。外層的 setInterval 每 10 秒把位置歸零,避免位移值不斷累積。

HTML

<div id="infozone">
  <div>
    C# 滑鼠屬性動態操作相關原始碼示例,比如隱藏與顯示滑鼠指標、
    將滑鼠左右鍵功能互換、更換滑鼠指標形狀、呼叫 Windows 滑鼠設定面板等,
    小技巧,多多益善。
  </div>
</div>

現代寫法建議

這套寫法在当年很實用,但今天有更好的選擇:純 CSS 的 @keyframes 搭配 transform: translateX() 就能做出同樣效果,而且交由 GPU 合成,效能與平順度都更好,還能自動適應內容長度。若需要「滑鼠移入暫停」,加一行 animation-play-state: paused 即可,不必像上例那樣手動管理一堆 setTimeout 編號。

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