DIV CSS 佈局教程網

純 JavaScript 打造上下左右四向無縫滾動公告列表
編輯:關於JavaScript     

首頁的公告欄、跑馬燈常需要無縫捲動。這裡不使用任何動畫外掛,只用 jQuery 做 DOM 操作與計時器,封裝一個可設定「水平/垂直」與「方向」的 scroll() 函式,同一份程式碼就能驅動多個不同行為的列表。

一、HTML 與 CSS

<style>
  * { margin: 0; padding: 0; }
  body { padding: 20px; }
  .textbox { border: 1px solid #ddd; width: auto; overflow: hidden; }
  .textbox ul { list-style: none; position: relative; }
  .textbox ul li { padding: 5px 0; }
</style>

<div id="textbox" class="textbox">
  <ul>
    <li>汽車 | 運動B級車降3萬5</li>
    <li>家居 | 這麼厲害的裝修 女人真的要坐不住了</li>
    <li>教育 | 各省前三報考華工重獎10萬元/人</li>
    <li>健康 | 濫用激素釀苦果 14歲男孩10年不長個兒</li>
    <li>運動 | 恆大亞冠生死戰 猜比分贏正版球衣</li>
  </ul>
  <a href="#" class="btnPrev">向左</a>
  <a href="#" class="btnNext">向右</a>
</div>

<div id="textbox2" class="textbox">
  <ul><!-- 結構同上 --></ul>
  <a href="#" class="btnPrev">向上</a>
  <a href="#" class="btnNext">向下</a>
</div>

二、呼叫方式

// 水平向右捲動,可見 2 筆
scroll('#textbox', { vis: 2, btnHidden: false, dir: 'prev', type: 'h' });
// 垂直向上捲動,可見 3 筆
scroll('#textbox2', { vis: 3, btnHidden: false, dir: 'prev', type: 'v' });

三、核心思路:複製節點換位移

無縫的關鍵在於「複製」:把最後一筆複製到最前面,再把前 vis 筆複製到最後,容器初始位移設為 -lastCloneHeight(或寬度)。當位移推到 -(LiHeight + lastCloneHeight) 時,畫面剛好回到與起點完全一致的狀態,此時把位移重設回去,視覺上就察覺不到接縫。

function scroll(container, options) {
  var box = $(container);
  var boxUl = box.find('ul').eq(0);
  var LiHeight = 0, cloneLiHeight = 0;      // 垂直方向尺寸
  var LiWidth = 0, cloneLiWidth = 0;        // 水平方向尺寸
  var Lis = boxUl.children();
  var btnPrev = box.find('.btnPrev');
  var btnNext = box.find('.btnNext');

  var defult = {
    vis: 2,            // 顯示筆數
    autoPlay: true,    // 自動播放
    speed: 50,         // 滾動間隔(毫秒)
    dir: 'prev',       // 滾動方向
    btnHidden: false,  // 是否隱藏按鈕
    type: 'v'          // v 垂直、h 水平
  };
  var opt = $.extend({}, defult, options);

  var lastClone = 0, lastCloneHeight = 0, allCloneHeight = 0;
  var lastCloneWidth = 0, allCloneWidth = 0;
  var visHeight = 0, visWidth = 0, boxUl_wrap;

  if (opt.type === "v") {
    Lis.each(function () { $(this).height($(this).height()); LiHeight += $(this).outerHeight(true); });
    lastClone = boxUl.children(':last').clone().addClass('clone').prependTo(boxUl);
    lastCloneHeight = lastClone.outerHeight(true);
    allCloneHeight = lastClone.outerHeight(true);
    for (var i = 0; i < opt.vis; i++) {
      Lis.eq(i).clone().addClass('clone').appendTo(boxUl);
      allCloneHeight += Lis.eq(i).outerHeight(true);
    }
    visHeight = allCloneHeight - lastCloneHeight;
    cloneLiHeight = LiHeight + allCloneHeight;
    boxUl_wrap = $('<div></div>').css({ 'width': '100%', 'height': visHeight, 'overflow': 'hidden', 'position': 'relative' }).attr('id', 'ulWrap');
    boxUl.css({ 'height': cloneLiHeight, 'top': -lastCloneHeight }).wrap(boxUl_wrap);
  } else if (opt.type === "h") {
    Lis.css({ 'whiteSpace': 'nowrap', 'float': 'left', 'paddingRight': '10px' });
    Lis.each(function () { $(this).width($(this).width()); LiWidth += $(this).outerWidth(true); });
    lastClone = boxUl.children(':last').clone().addClass('clone').prependTo(boxUl);
    lastCloneWidth = lastClone.outerWidth(true);
    allCloneWidth = lastClone.outerWidth(true);
    for (var j = 0; j < opt.vis; j++) {
      Lis.eq(j).clone().addClass('clone').appendTo(boxUl);
      allCloneWidth += Lis.eq(j).outerWidth(true);
    }
    visHeight = Lis.eq(0).outerHeight(true);
    visWidth = allCloneWidth - lastCloneWidth;
    cloneLiWidth = LiWidth + allCloneWidth;
    boxUl_wrap = $('<div></div>').css({ 'width': visWidth, 'height': visHeight, 'overflow': 'hidden', 'position': 'relative' }).attr('id', 'ulWrap');
    boxUl.css({ 'width': cloneLiWidth, 'left': -lastCloneWidth }).wrap(boxUl_wrap);
    box.css({ 'width': visWidth });
  }

  var timer = null;
  var scrollTop = function () {
    clearInterval(timer);
    timer = setInterval(function () {
      var tmp = parseInt(boxUl.css('top').replace('px', "")) - 1;
      boxUl.animate({ 'top': tmp }, 0, function () {
        if (tmp <= -(LiHeight + lastCloneHeight)) { boxUl.css('top', -lastCloneHeight); }
      });
    }, opt.speed);
  };
  var scrollDown = function () {
    clearInterval(timer);
    timer = setInterval(function () {
      var tmp = parseInt(boxUl.css('top').replace('px', "")) + 1;
      boxUl.animate({ 'top': tmp }, 0, function () {
        if (tmp >= 0) { boxUl.css('top', -LiHeight); }
      });
    }, opt.speed);
  };
  var scrollLeft = function () {
    clearInterval(timer);
    timer = setInterval(function () {
      var tmp = parseInt(boxUl.css('left').replace('px', "")) - 1;
      boxUl.animate({ 'left': tmp }, 0, function () {
        if (tmp <= -(LiWidth + lastCloneWidth)) { boxUl.css('left', -lastCloneWidth); }
      });
    }, opt.speed);
  };
  var scrollRight = function () {
    clearInterval(timer);
    timer = setInterval(function () {
      var tmp = parseInt(boxUl.css('left').replace('px', "")) + 1;
      boxUl.animate({ 'left': tmp }, 0, function () {
        if (tmp >= 0) { boxUl.css('left', -LiWidth); }
      });
    }, opt.speed);
  };
  var scrollType = function (type, dir) {
    if (Lis.length >= opt.vis) { // 顯示筆數不能多於實際筆數,否則不啟動
      var sdir = typeof dir !== "undefined" ? dir : opt.dir;
      switch (type) {
        case "v": sdir === "prev" ? scrollTop() : scrollDown(); break;
        case "h": sdir === "prev" ? scrollLeft() : scrollRight();
      }
    }
  };

  if (opt.autoPlay) { scrollType(opt.type); }

  // 滑鼠移入暫停,移出恢復
  box.find('#ulWrap').hover(function () { clearInterval(timer); }, function () { scrollType(opt.type); });

  if (!opt.btnHidden) {
    btnPrev.unbind('mouseover').mouseover(function () { scrollType(opt.type, "prev"); });
    btnNext.unbind('mouseover').mouseover(function () { scrollType(opt.type, "next"); });
  } else {
    btnPrev.hide(); btnNext.hide();
  }
}

四、一個已知的相容性問題

原作者的案例在直接開啟時一切正常,但透過 document.write() 把整份程式碼寫入後執行,垂直模式的 li 高度用 height() 取到的值會不如預期,原因一直未能確認。實務上若要動態注入這類程式,建議改用 appendChild 或 innerHTML 掛載,並在 window.onload 之後再初始化,避開文件尚未完成解析就量測高度的時序問題。

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