萬盛學電腦網

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

移動端觸摸輪播圖:Zepto + RequireJS 實現手勢滑動切換

技術棧

  • Zepto.js:輕量級 jQuery 兼容庫,體積 ~9KB,專為移動端優化
  • RequireJS:AMD 模塊加載器,管理依賴與按需加載
  • CSS3 Transform/Transition:GPU 加速動畫,60fps 流暢體驗

HTML 結構

<div class="carousel-image">
  <div class="carousel-wrap"> <!-- 動畫容器 -->
    <a><img src="img1.jpg" alt=""/></a>
    <a><img src="img2.png" alt=""/></a>
    <a><img src="img3.jpg" alt=""/></a>
  </div>
  <div class="carousel-indicator"></div> <!-- 底部指示點 -->
</div>

核心模塊:carousel-image.js (AMD)

define(['$'], function($) {
  function CarouselImage() {
    this.config = {
      target: null,      // 容器選擇器/Zepto對象
      num: null,         // 指示點容器
      interval: 3000,    // 自動輪播間隔
      speed: 300,        // 動畫時長
      loop: true,        // 無限循環
      autoPlay: true
    };
    this.state = { index: 0, timer: null, width: 0, count: 0, moving: false };
  }

  CarouselImage.prototype.init = function(options) {
    $.extend(this.config, options);
    this.$target = $(this.config.target);
    this.$wrap = this.$target.find('.carousel-wrap');
    this.$items = this.$wrap.children();
    this.$num = $(this.config.num);
    this.state.count = this.$items.length;

    this._createIndicators();
    this._bindEvents();
    this._resize();
    if (this.config.autoPlay) this._startAutoPlay();

    $(window).on('resize', $.proxy(this._resize, this));
    return this;
  };

  CarouselImage.prototype._createIndicators = function() {
    var html = '';
    for (var i = 0; i < this.state.count; i++) html += '';
    this.$num.html(html);
  };

  CarouselImage.prototype._bindEvents = function() {
    var self = this;
    var $wrap = this.$wrap;

    // 觸摸滑動
    $wrap.on('touchstart', function(e) {
      self._touchStart(e.originalEvent.touches[0]);
    }).on('touchmove', function(e) {
      self._touchMove(e.originalEvent.touches[0]);
    }).on('touchend', function() {
      self._touchEnd();
    });

    // 指示點點擊
    this.$num.on('click', 'span', function() {
      self.goTo($(this).index());
    });

    // 鼠標拖拽(桌面調試用)
    $wrap.on('mousedown', function(e) {
      self._touchStart(e);
      $(document).on('mousemove.carousel', function(e) { self._touchMove(e); })
                .one('mouseup.carousel', function() { $(document).off('mousemove.carousel'); self._touchEnd(); });
    });
  };

  CarouselImage.prototype._resize = function() {
    this.state.width = this.$target.width();
    this.$items.width(this.state.width);
    this.$wrap.width(this.state.width * this.state.count);
    this.goTo(this.state.index, false); // 重新定位無動畫
  };

  CarouselImage.prototype._touchStart = function(touch) {
    this.state.startX = touch.clientX;
    this.state.startTime = Date.now();
    this.state.moving = false;
    this.$wrap.css('transition', 'none'); // 取消動畫跟手
    clearTimeout(this.state.timer);
  };

  CarouselImage.prototype._touchMove = function(touch) {
    var dx = touch.clientX - this.state.startX;
    if (Math.abs(dx) > 10) this.state.moving = true; // 閾值防誤觸
    var targetX = -this.state.index * this.state.width + dx;
    // 邊界阻尼
    if (this.state.index === 0 && dx > 0) targetX = dx * 0.3;
    if (this.state.index === this.state.count - 1 && dx < 0) targetX = -this.state.index * this.state.width + dx * 0.3;
    this.$wrap.css('transform', 'translate3d(' + targetX + 'px, 0, 0)');
  };

  CarouselImage.prototype._touchEnd = function() {
    if (!this.state.moving) return;
    var dx = event.changedTouches ? event.changedTouches[0].clientX - this.state.startX : 0;
    var dt = Date.now() - this.state.startTime;
    var threshold = this.state.width * 0.2; // 20% 閾值
    var nextIndex = this.state.index;

    if (dt < 300 && Math.abs(dx) > threshold) {
      nextIndex += dx > 0 ? -1 : 1; // 快速滑動
    } else if (Math.abs(dx) > this.state.width / 2) {
      nextIndex += dx > 0 ? -1 : 1; // 滑動超過半屏
    }

    this.goTo(nextIndex);
    if (this.config.autoPlay) this._startAutoPlay();
  };

  CarouselImage.prototype.goTo = function(index, animate) {
    animate = animate !== false;
    index = Math.max(0, Math.min(index, this.state.count - 1));
    this.state.index = index;
    var x = -index * this.state.width;
    this.$wrap.css({
      transition: animate ? 'transform ' + this.config.speed + 'ms cubic-bezier(0.4, 0, 0.2, 1)' : 'none',
      transform: 'translate3d(' + x + 'px, 0, 0)'
    });
    this.$num.find('span').removeClass('active').eq(index).addClass('active');
  };

  CarouselImage.prototype._startAutoPlay = function() {
    var self = this;
    clearTimeout(this.state.timer);
    this.state.timer = setTimeout(function() {
      var next = (self.state.index + 1) % self.state.count;
      self.goTo(next);
      self._startAutoPlay();
    }, this.config.interval);
  };

  return CarouselImage;
});

調用方式

<script>
requirejs.config({ baseUrl: '../src', paths: { $: 'zepto' } });
require(['carousel-image', '$'], function(CarouselImage, $) {
  var carousel = new CarouselImage();
  carousel.init({ target: '.carousel-image', num: '.carousel-indicator', interval: 4000 });
});
</script>

關鍵技術點解析

  1. translate3d + transition:GPU 加速,避免重繪回流,動畫極其流暢。
  2. 觸摸跟手:touchmove 中實時更新 transform,transition: none 取消動畫延遲。
  3. 邊界阻尼:首尾滑動時位移乘以 0.3,體現「拉扯感」。
  4. 閾值判斷:結合滑動距離(>20% 寬度)與時長(<300ms)判斷是否切換。
  5. 自動播放與暫停:觸摸開始清除定時器,結束後重啟。
  6. Resize 重算:容器寬度變化時重新計算 item 寬度並重新定位。

無依賴原生 JS 精簡版

class SimpleCarousel {
  constructor(el) { this.el = el; this.wrap = el.querySelector('.carousel-wrap'); this.items = [...this.wrap.children]; this.idx = 0; this.bind(); this.resize(); }
  bind() {
    let startX, startTime, moving;
    this.wrap.addEventListener('touchstart', e => { startX = e.touches[0].clientX; startTime = Date.now(); moving = false; this.wrap.style.transition = 'none'; });
    this.wrap.addEventListener('touchmove', e => { let dx = e.touches[0].clientX - startX; if (Math.abs(dx)>10) moving=true; this.wrap.style.transform = `translate3d(${-this.idx*this.width+dx}px,0,0)`; });
    this.wrap.addEventListener('touchend', e => { if (!moving) return; let dx = e.changedTouches[0].clientX - startX; let next = this.idx + (dx>0?-1:1); this.go(Math.max(0,Math.min(next,this.items.length-1))); });
    window.addEventListener('resize', () => this.resize());
  }
  resize() { this.width = this.el.clientWidth; this.items.forEach(i => i.style.width = this.width+'px'); this.wrap.style.width = this.width*this.items.length+'px'; this.go(this.idx,false); }
  go(idx, animate=true) { this.idx=idx; this.wrap.style.transition=animate?'transform .3s':''; this.wrap.style.transform=`translate3d(${-idx*this.width}px,0,0)`; }
}
new SimpleCarousel(document.querySelector('.carousel-image'));

總結

移動端輪播核心在於「CSS3 3D 變換 + 觸摸事件 + 閾值判斷 + 自動播放狀態機」。Zepto/RequireJS 版適合模塊化老項目,新項目建議用原生 ES6 類 + CSS Scroll Snap 或成熟庫。理解核心邏輯後,可輕鬆擴展縮放、淡入淡出、3D 翻轉等多種切換效果。

copyright © 萬盛學電腦網 all rights reserved