返回 jQuery 实例与特效代码列表
图片与媒体MIT兼容 jQuery 1.12 / 3.8 / 4.1

轮播图

支持左右切换按钮、底部指示点、自动播放与鼠标悬停暂停的无缝轮播图组件。

兼容性说明:使用 CSS transform 位移,全版本兼容且支持 slim 精简版。

在线交互演示(独立沙箱)

$(function () {
  var $box = $('#demo-carousel');
  var $track = $box.find('.track');
  var total = $box.find('.slide').length;
  var idx = 0, timer = null;

  function go(n) {
    idx = (n + total) % total;
    $track.css('transform', 'translateX(-' + (idx * 100) + '%)');
    $box.find('.dot').removeClass('active').eq(idx).addClass('active');
  }
  function start() { timer = setInterval(function () { go(idx + 1); }, 3200); }
  function stop() { clearInterval(timer); }

  $box.find('.prev').on('click', function () { go(idx - 1); });
  $box.find('.next').on('click', function () { go(idx + 1); });
  $box.on('click', '.dot', function () { go(Number($(this).data('i'))); });
  $box.on('mouseenter', stop).on('mouseleave', start);
  start();
});
不用 jQuery 怎么写?(现代原生 JS / CSS 替代思路)

使用 CSS scroll-snap-type: x mandatory 配合容器 scrollTo({ behavior: 'smooth' }) 即可实现原生丝滑轮播。

track.scrollTo({ left: index * track.clientWidth, behavior: 'smooth' });