DIV CSS 佈局教程網

基於 jQuery 的文字跑馬燈插件(單頁多滾動區)
編輯:JQuery特效代碼     

這個輕量的文字滾動插件相容各瀏覽器的行高差異,並支援在同一頁面中同時存在多個獨立運作的滾動區,適合用於公告欄、最新消息等需要循環播放文字的地方。

插件程式碼

(function($){
  $.fn.extend({
    RollTitle: function(opt, callback){
      if(!opt) var opt = {};
      var _this = this;
      _this.timer = null;
      _this.lineH = _this.find("li:first").height();
      _this.line = opt.line ? parseInt(opt.line,10) : parseInt(_this.height()/_this.lineH,10);
      _this.speed = opt.speed ? parseInt(opt.speed,10) : 3000;   // 卷動速度,數值越大越慢(毫秒)
      _this.timespan = opt.timespan ? parseInt(opt.timespan,10) : 5000; // 滾動間隔(毫秒)
      if(_this.line == 0) _this.line = 1;
      _this.upHeight = 0 - _this.line * _this.lineH;
      _this.scrollUp = function(){
        _this.animate({ marginTop: _this.upHeight }, _this.speed, function(){
          for(i=1; i<=_this.line; i++){
            _this.find("li:first").appendTo(_this);
          }
          _this.css({ marginTop: 0 });
        });
      };
      _this.hover(function(){
        clearInterval(_this.timer);
      }, function(){
        _this.timer = setInterval(function(){ _this.scrollUp(); }, _this.timespan);
      }).mouseout();
    }
  });
})(jQuery);

參數說明

呼叫時可傳入三個參數:

  • line:一次卷動的文字行數。
  • speed:卷動動畫的時間。
  • timespan:兩次滾動之間的間隔時間。

使用範例

<ul id="RunTopic">
  <li>文字1</li>
  <li>文字2</li>
  <li>文字3</li>
  <li>文字4</li>
  <li>文字5</li>
</ul>
<script>
$(document.body).ready(function(){
  $("#RunTopic").RollTitle({ line:1, speed:200, timespan:1500 });
});
</script>

它的原理是透過 animate 改變 ul 的 marginTop 值讓文字向上捲動,動畫結束後再把已捲出的 li 移到列表末尾並重置位置,形成無縫循環。滑鼠移入時自動暫停、移出後恢復,兼顧了閱讀與展示的需求。由於每個滾動區各自維護自己的計時器,因此同一頁面上多個跑馬燈可以互不干擾地獨立運作。

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