萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 實現無縫無限循環滾動完整教學(支援四向滾動)

jQuery 打造高效能無縫無限循環滾動元件

無縫滾動是展示新聞列表、產品輪播、公告跑馬燈的經典需求。本文詳細解析如何使用 jQuery animate 實現高效能、支援四向滾動的無限循環元件,並提供完整參數化配置方案。

核心實作邏輯

利用 animate() 移動容器 margin-left(或 margin-top),動畫完成後將第一個子元素移至末尾,並重置 margin 為 0,形成視覺上的無限循環。

完整程式碼實作

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>無縫滾動範例</title>
  <script src="jquery-1.7.2.min.js"></script>
  <style>
    * { margin: 0; padding: 0; }
    li { list-style: none; }
    .content { 
      width: 1020px; 
      height: 112px; 
      overflow: hidden; 
      border: #4e83c2 solid 1px; 
      margin: 50px auto; 
      position: relative;
    }
    .content ul { 
      width: 1020px; 
      height: 100px; 
      position: absolute; 
      left: 0; 
      top: 0;
    }
    .content ul li { 
      float: left; 
      width: 100px; 
      height: 100px; 
      border: #ccc solid 1px; 
      display: block; 
      margin: 5px; 
      box-sizing: border-box;
      text-align: center;
      line-height: 100px;
      font-size: 24px;
      color: #666;
    }
  </style>
</head>
<body>
  <div class="content">
    <ul>
      <li>1</li><li>2</li><li>3</li><li>4</li><li>5</li>
      <li>6</li><li>7</li><li>8</li><li>9</li><li>10</li>
      <li>11</li><li>12</li><li>13</li><li>14</li><li>15</li>
      <li>16</li><li>17</li><li>18</li><li>19</li><li>20</li>
      <li>21</li><li>22</li><li>23</li><li>24</li>
    </ul>
  </div>

  <script>
    // 核心滾動函式
    function scroll() {
      $('.content ul').animate({
        'margin-left': '-110px'  // 單項寬度 100px + margin 10px
      }, function() {
        // 動畫完成回呼:移動第一項到末尾,重置 margin
        $('.content ul li:first').appendTo('.content ul');
        $('.content ul').css({'margin-left': 0});
      });
    }

    // 啟動定時器(1000ms = 1秒間隔)
    setInterval(scroll, 1000);
  </script>
</body>
</html>

四向滾動配置對照表

方向animate 參數重置 CSS移動邏輯
向左{'margin-left': '-110px'}{'margin-left': 0}first → appendTo
向右{'margin-left': '110px'}{'margin-left': 0}last → prependTo
向上{'margin-top': '-105px'}{'margin-top': 0}first → appendTo
向下{'margin-top': '105px'}{'margin-top': 0}last → prependTo

進階參數化元件封裝

$.fn.seamlessScroll = function(options) {
  var settings = $.extend({
    direction: 'left',      // left, right, up, down
    speed: 1000,            // 動畫間隔(ms)
    duration: 500,          // 動畫持續時間(ms)
    itemSelector: 'li',     // 項目選取器
    containerSelector: 'ul', // 容器選取器
    pauseOnHover: true      // 滑鼠懸停暫停
  }, options);

  return this.each(function() {
    var $wrap = $(this);
    var $container = $wrap.find(settings.containerSelector);
    var $items = $container.find(settings.itemSelector);
    var itemCount = $items.length;
    if (itemCount < 2) return; // 少於2項無需滾動

    // 計算單項尺寸(含 margin)
    var firstItem = $items.first();
    var itemWidth = firstItem.outerWidth(true);
    var itemHeight = firstItem.outerHeight(true);

    var timer, isHover = false;

    function doScroll() {
      if (isHover) return;
      
      var animateProps = {};
      var resetProps = {};
      var moveFn;

      switch (settings.direction) {
        case 'left':
          animateProps['margin-left'] = -itemWidth;
          resetProps['margin-left'] = 0;
          moveFn = function() { $container.find(settings.itemSelector + ':first').appendTo($container); };
          break;
        case 'right':
          animateProps['margin-left'] = itemWidth;
          resetProps['margin-left'] = 0;
          moveFn = function() { $container.find(settings.itemSelector + ':last').prependTo($container); };
          break;
        case 'up':
          animateProps['margin-top'] = -itemHeight;
          resetProps['margin-top'] = 0;
          moveFn = function() { $container.find(settings.itemSelector + ':first').appendTo($container); };
          break;
        case 'down':
          animateProps['margin-top'] = itemHeight;
          resetProps['margin-top'] = 0;
          moveFn = function() { $container.find(settings.itemSelector + ':last').prependTo($container); };
          break;
      }

      $container.animate(animateProps, settings.duration, function() {
        moveFn();
        $container.css(resetProps);
      });
    }

    // 啟動
    timer = setInterval(doScroll, settings.speed);

    // 滑鼠懸停暫停
    if (settings.pauseOnHover) {
      $wrap.hover(
        function() { isHover = true; },
        function() { isHover = false; }
      );
    }

    // 公開方法:銷毀
    $wrap.data('seamlessScroll', {
      destroy: function() { clearInterval(timer); }
    });
  });
};

// 使用範例
$('.content').seamlessScroll({
  direction: 'left',
  speed: 2000,
  duration: 800
});

效能優化關鍵點

  • 使用 absolute 定位:容器設為 position: absolute,移動時不觸發父層重排
  • 硬體加速:給容器加上 transform: translateZ(0) 或 will-change: transform
  • 避免佈局抖動:讀寫分離,批次操作 DOM
  • 請求動畫幀優化:複雜場景考慮 requestAnimationFrame 手動控制

無障礙與使用者體驗增強

  1. 加入 aria-live="polite" 輔助閱讀器播報
  2. 提供暫停/播放控制按鈕
  3. 鍵盤操作支援(空白鍵切換播放狀態)
  4. 減少動畫偏好設定媒體查詢:@media (prefers-reduced-motion: reduce)
copyright © 萬盛學電腦網 all rights reserved