DIV CSS 佈局教程網

JavaScript 實現圖片列表左右滾動(含自動播放與滑鼠暫停)
編輯:關於JavaScript     

首頁常有「一排商品橫向排列、點箭頭往來捲動」的需求。與其一次載入全部再隱藏,不如做真正的位移滾動,讓它看起來像一條持續移動的展示帶。這份實作拆成 HTML 結構、scroll_img.js 邏輯與 global.css 樣式三個檔案。

HTML 結構(index.html)

左右各一顆箭頭按鈕,中間是可視區域,裡面放一條超寬的 ul:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="css/global.css" />
<script type="text/javascript" src="js/jquery-1.7.min.js"></script>
<script type="text/javascript" src="js/scroll_img.js"></script>
<title>圖片列表滾動</title>
</head>
<body>
<div class="scroll_img_wrap clearfix">

  <p class="left_btn">
    <a href="javascript:void(0)"><img src="images/btn.jpg" alt="上一頁" /></a>
  </p>

  <div id="scroll_img">
    <ul class="scroll_img_list clearfix">
      <li><p><a href="#"><img src="images/1.jpg" alt="" /></a></p>
          <p><a href="#">information1</a></p></li>
      <li><p><a href="#"><img src="images/1.jpg" alt="" /></a></p>
          <p><a href="#">information2</a></p></li>
      <li><p><a href="#"><img src="images/2.jpg" alt="" /></a></p>
          <p><a href="#">information5</a></p></li>
      <!-- 其餘項目依此類推,共 14 筆 -->
    </ul>
  </div>

  <p class="right_btn">
    <a href="javascript:void(0)"><img src="images/btn.jpg" alt="下一頁" /></a>
  </p>

</div>

<script type="text/javascript">
(function(){
  // 參數依序為:容器 id、每次移動距離、可視寬度、單項寬度、項目間距
  var test = new scroll_img('scroll_img', 150, 590, 140, 10);
  test.initialize();

  $('.left_btn').click(function(){
    test.stop(); test.left(); test.autoplay();
  });
  $('.right_btn').click(function(){
    test.stop(); test.right(); test.autoplay();
  });
})();
</script>
</body>
</html>

滾動邏輯(scroll_img.js)

function scroll_img(target, distance, show_width, li_width, mr){
  this.distance   = distance;     // 每次移動距離
  this.target     = $("#" + target);
  this.show_width = show_width;   // 可視區域寬度
  this.li_width   = li_width;     // 單一項目寬度
  this.mr         = mr;           // 項目間距
  this.scrollbar  = this.target.find('ul');
  this.position   = 0;            // 目前的 left 偏移(負值代表往右捲)
  this.direction  = 1;            // 1 表示向右前進,-1 表示折返
}

scroll_img.prototype = {

  version: 1.00,

  initialize: function(){
    var t = this;
    t.scrollbar.css('position', 'relative');
    t.autoplay();

    // 滑鼠移入暫停,移出恢復
    t.scrollbar.mouseover(function(){ t.stop(); });
    t.scrollbar.mouseout (function(){ t.autoplay(); });
  },

  // 可捲動的總長度
  total_length: function(){
    var t = this;
    var total_num = t.scrollbar.find('li').length;
    return total_num * (t.li_width + t.mr) - (t.mr + t.show_width);
  },

  // 往「後」捲(position 變小)
  right: function(){
    var t = this;
    (-t.position) < t.total_length() ? t.position -= t.distance : t.position = t.position;

    if ((-t.position) < t.total_length()) {
      t.scrollbar.animate({ left: t.position }, 500);
      t.direction = 1;
    }
    if ((-t.position) == t.total_length()) {
      t.scrollbar.animate({ left: t.position }, 500);
      t.direction = -1;      // 到底就折返
    }
  },

  // 往「前」捲(position 變大)
  left: function(){
    var t = this;
    (-t.position) > 0 ? t.position += t.distance : t.position = t.position;

    if ((-t.position) > 0) {
      t.scrollbar.animate({ left: t.position }, 500);
      t.direction = -1;
    }
    if ((-t.position) == 0) {
      t.scrollbar.animate({ left: t.position }, 500);
      t.direction = 1;       // 回到頭也折返
    }
  },

  // 自動播放
  autoplay: function(){
    var t = this;
    t.setInt = setInterval(function(){
      t.direction == 1 ? t.right() : t.left();
    }, 3000);
  },

  stop: function(){
    var t = this;
    clearInterval(t.setInt);
  }
};

樣式(global.css)

/* ---------- reset ---------- */
body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,p,blockquote,th,td{
  margin:0; padding:0; font-family:arial,"微軟雅黑";
}
table{ border-collapse:collapse; border-spacing:0; }
fieldset,img{ border:0; }
ol,ul{ list-style-type:none; }
h1,h2,h3,h4,h5,h6{ font-size:100%; font-weight:normal; }

/* ---------- clearfix ---------- */
.clearfix:after{
  content:"."; display:block; height:0; clear:both; visibility:hidden;
}
.clearfix{ display:inline-block; }
* html .clearfix{ height:1%; }
.clearfix{ display:block; }

/* ---------- 主體 ---------- */
.scroll_img_wrap{ width:612px; margin:10px auto; }

/* 可視區域:關鍵是 overflow:hidden,超出的部分被裁掉 */
#scroll_img{
  width:590px;
  overflow:hidden;
  float:left;
  border:1px #ccc solid;
}

/* ul 要遠比容器寬,才能承載橫向排列的所有項目 */
.scroll_img_list{ width:9999px; }

.scroll_img_list li{ float:left; width:140px; margin-right:10px; }
.scroll_img_list li p{ text-align:center; }
.scroll_img_list li p a{ text-decoration:none; color:#666; }

.left_btn, .right_btn{ float:left; }

運作原理拆解

1. 裁切 + 位移。外層 #scroll_img 用 overflow:hidden 把超出部分藏起來,內層 ul 寬度設成 9999px 讓所有 li 橫向鋪開,再透過改變 ul 的 left 值製造捲動錯覺。

2. direction 達到自動折返。不必額外寫「判斷是否到頭再反向」的邏輯,direction 變數記住前進方向,到邊界時翻轉即可,往復循環。

3. total_length 的算法。總寬 = 項目數 × (單項寬 + 間距) − (間距 + 可視寬度),減掉最後一筆的間距與可視區寬,才能得到「剛好捲到底」的正確距離。

4. 點擊時先 stop 再 autoplay。避免連續點擊造成多個 setInterval 並存,位移相互打架。

可以改進的地方

1. 停手動不要重啟計時器。目前 mouseout 一律呼叫 autoplay,若滑鼠只是從列表移到箭頭上就會重新開始,體驗略顯突兀。可加一個「使用者是否正在操作」的旗標。

2. width: 9999px 是硬編碼。項目數量變動時要重新算。建議在 initialize 中動態計算 li.length * (li_width + mr) 後設定,並用它取代 total_length 的估算。

3. jQuery 1.7 太舊。其中的 mouseover/mouseout 有前述的泡泡問題,改用 hover 或 mouseenter/mouseleave 更準確。

4. 可用 CSS 大幅簡化。把 ul 改成 display:flex; overflow-x:auto; scroll-snap-type:x mandatory;,再搭配 scrollBy({left: 150, behavior:'smooth'}),幾乎不需要寫自製動畫。

5. 記得補上鍵盤與觸控支援。左右方向鍵、螢幕閱讀器的 aria-label、以及行動端的滑動手勢,都是實務上必須考慮的。

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