刷卡API

If you are upgrading from Swiper 9 to Swiper 10, check out Migration Guide to Swiper 10

Swiper 完整 HTML 布局

¥Swiper Full HTML Layout

<!-- Slider main container -->
<div class="swiper">
  <!-- Additional required wrapper -->
  <div class="swiper-wrapper">
    <!-- Slides -->
    <div class="swiper-slide">Slide 1</div>
    <div class="swiper-slide">Slide 2</div>
    <div class="swiper-slide">Slide 3</div>
    ...
  </div>
  <!-- If we need pagination -->
  <div class="swiper-pagination"></div>

  <!-- If we need navigation buttons -->
  <div class="swiper-button-prev"></div>
  <div class="swiper-button-next"></div>

  <!-- If we need scrollbar -->
  <div class="swiper-scrollbar"></div>
</div>

样式

¥Styles

Swiper 包包含不同的 CSS、Less 和 SCSS 样式集:

¥Swiper package contains different sets of CSS, Less and SCSS styles:

CSS 样式

¥CSS Styles

bundle 版本的 CSS 样式:

¥CSS styles for bundle version:

  • swiper-bundle.css - 所有 Swiper 样式,包括所有模块样式(例如导航、分页等)

    ¥swiper-bundle.css - all Swiper styles including all modules styles (like Navigation, Pagination, etc.)

  • swiper-bundle.min.css - 与上一个相同,但已最小化

    ¥swiper-bundle.min.css - same as previous but minified

bundle 版本的 CSS 样式(包导入):

¥CSS styles for bundle version (package imports):

  • swiper/css - 所有 Swiper 样式,包括所有模块样式(例如导航、分页等)

    ¥swiper/css - all Swiper styles including all modules styles (like Navigation, Pagination, etc.)

  • swiper/css/bundle - 与上一个相同,但已最小化

    ¥swiper/css/bundle - same as previous but minified

核心版本和模块的 CSS 样式(包导入):

¥CSS styles for core version and modules (package imports):

  • swiper/css - 仅核心 Swiper 样式

    ¥swiper/css - only core Swiper styles

  • swiper/css/a11y - A11y 模块所需样式

    ¥swiper/css/a11y - styles required for A11y module

  • swiper/css/autoplay - 自动播放模块所需样式

    ¥swiper/css/autoplay - styles required for Autoplay module

  • swiper/css/controller - 控制器模块所需样式

    ¥swiper/css/controller - styles required for Controller module

  • swiper/css/effect-cards - 卡片效果模块所需样式

    ¥swiper/css/effect-cards - styles required for Cards Effect module

  • swiper/css/effect-coverflow - Coverflow 效果模块所需样式

    ¥swiper/css/effect-coverflow - styles required for Coverflow Effect module

  • swiper/css/effect-creative - 创意效果模块所需样式

    ¥swiper/css/effect-creative - styles required for Creative Effect module

  • swiper/css/effect-cube - 立方体效果模块所需样式

    ¥swiper/css/effect-cube - styles required for Cube Effect module

  • swiper/css/effect-fade - 所需样式淡入淡出效果模块

    ¥swiper/css/effect-fade - styles required for Fade Effect module

  • swiper/css/effect-flip - 翻转效果模块所需样式

    ¥swiper/css/effect-flip - styles required for Flip Effect module

  • swiper/css/free-mode - 自由模式模块所需样式

    ¥swiper/css/free-mode - styles required for Free Mode module

  • swiper/css/grid - 网格模块所需样式

    ¥swiper/css/grid - styles required for Grid module

  • swiper/css/hash-navigation - 哈希导航模块所需样式

    ¥swiper/css/hash-navigation - styles required for Hash Navigation module

  • swiper/css/history - 历史记录模块所需样式

    ¥swiper/css/history - styles required for History module

  • swiper/css/keyboard - 键盘模块所需样式

    ¥swiper/css/keyboard - styles required for Keyboard module

  • swiper/css/manipulation - 操作模块所需样式

    ¥swiper/css/manipulation - styles required for Manipulation module

  • swiper/css/mousewheel - 鼠标滚轮模块所需样式

    ¥swiper/css/mousewheel - styles required for Mousewheel module

  • swiper/css/navigation - 导航模块所需样式

    ¥swiper/css/navigation - styles required for Navigation module

  • swiper/css/pagination - 分页模块所需样式

    ¥swiper/css/pagination - styles required for Pagination module

  • swiper/css/parallax - 视差模块所需样式

    ¥swiper/css/parallax - styles required for Parallax module

  • swiper/css/scrollbar - 滚动条模块所需样式

    ¥swiper/css/scrollbar - styles required for Scrollbar module

  • swiper/css/thumbs - 缩略图模块所需样式

    ¥swiper/css/thumbs - styles required for Thumbs module

  • swiper/css/virtual - 虚拟模块所需样式

    ¥swiper/css/virtual - styles required for Virtual module

  • swiper/css/zoom - 缩放模块所需样式

    ¥swiper/css/zoom - styles required for Zoom module

更少样式

¥Less Styles

Less 样式是核心版本和模块(包导入)的独立样式:

¥Less styles are separate styles for core version and modules (package imports):

  • swiper/less - 仅核心 Swiper 样式

    ¥swiper/less - only core Swiper styles

  • swiper/less/bundle - 所有 Swiper 样式,包括所有模块样式(例如导航、分页等)

    ¥swiper/less/bundle - all Swiper styles including all modules styles (like Navigation, Pagination, etc.)

  • swiper/less/a11y - A11y 模块所需样式

    ¥swiper/less/a11y - styles required for A11y module

  • swiper/less/autoplay - 自动播放模块所需样式

    ¥swiper/less/autoplay - styles required for Autoplay module

  • swiper/less/controller - 控制器模块所需样式

    ¥swiper/less/controller - styles required for Controller module

  • swiper/less/effect-cards - 卡片效果模块所需样式

    ¥swiper/less/effect-cards - styles required for Cards Effect module

  • swiper/less/effect-coverflow - Coverflow 效果模块所需样式

    ¥swiper/less/effect-coverflow - styles required for Coverflow Effect module

  • swiper/less/effect-creative - 创意效果模块所需样式

    ¥swiper/less/effect-creative - styles required for Creative Effect module

  • swiper/less/effect-cube - 立方体效果模块所需样式

    ¥swiper/less/effect-cube - styles required for Cube Effect module

  • swiper/less/effect-fade - 所需样式淡入淡出效果模块

    ¥swiper/less/effect-fade - styles required for Fade Effect module

  • swiper/less/effect-flip - 翻转效果模块所需样式

    ¥swiper/less/effect-flip - styles required for Flip Effect module

  • swiper/less/free-mode - 自由模式模块所需样式

    ¥swiper/less/free-mode - styles required for Free Mode module

  • swiper/less/grid - 网格模块所需样式

    ¥swiper/less/grid - styles required for Grid module

  • swiper/less/hash-navigation - 哈希导航模块所需样式

    ¥swiper/less/hash-navigation - styles required for Hash Navigation module

  • swiper/less/history - 历史记录模块所需样式

    ¥swiper/less/history - styles required for History module

  • swiper/less/keyboard - 键盘模块所需样式

    ¥swiper/less/keyboard - styles required for Keyboard module

  • swiper/less/manipulation - 操作模块所需样式

    ¥swiper/less/manipulation - styles required for Manipulation module

  • swiper/less/mousewheel - 鼠标滚轮模块所需样式

    ¥swiper/less/mousewheel - styles required for Mousewheel module

  • swiper/less/navigation - 导航模块所需样式

    ¥swiper/less/navigation - styles required for Navigation module

  • swiper/less/pagination - 分页模块所需样式

    ¥swiper/less/pagination - styles required for Pagination module

  • swiper/less/parallax - 视差模块所需样式

    ¥swiper/less/parallax - styles required for Parallax module

  • swiper/less/scrollbar - 滚动条模块所需样式

    ¥swiper/less/scrollbar - styles required for Scrollbar module

  • swiper/less/thumbs - 缩略图模块所需样式

    ¥swiper/less/thumbs - styles required for Thumbs module

  • swiper/less/virtual - 虚拟模块所需样式

    ¥swiper/less/virtual - styles required for Virtual module

  • swiper/less/zoom - 缩放模块所需样式

    ¥swiper/less/zoom - styles required for Zoom module

SCSS 样式

¥SCSS Styles

SCSS 样式在核心版本和模块(包导入)中也是单独的样式:

¥SCSS styles are also separate styles for core version and modules (package imports):

  • swiper/scss - 仅核心 Swiper 样式

    ¥swiper/scss - only core Swiper styles

  • swiper/scss/bundle - 所有 Swiper 样式,包括所有模块样式(例如导航、分页等)

    ¥swiper/scss/bundle - all Swiper styles including all modules styles (like Navigation, Pagination, etc.)

  • swiper/scss/a11y - A11y 模块所需样式

    ¥swiper/scss/a11y - styles required for A11y module

  • swiper/scss/autoplay - 自动播放模块所需样式

    ¥swiper/scss/autoplay - styles required for Autoplay module

  • swiper/scss/controller - 控制器模块所需样式

    ¥swiper/scss/controller - styles required for Controller module

  • swiper/scss/effect-cards - 卡片效果模块所需样式

    ¥swiper/scss/effect-cards - styles required for Cards Effect module

  • swiper/scss/effect-coverflow - Coverflow 效果模块所需样式

    ¥swiper/scss/effect-coverflow - styles required for Coverflow Effect module

  • swiper/scss/effect-creative - 创意效果模块所需样式

    ¥swiper/scss/effect-creative - styles required for Creative Effect module

  • swiper/scss/effect-cube - 立方体效果模块所需样式

    ¥swiper/scss/effect-cube - styles required for Cube Effect module

  • swiper/scss/effect-fade - 所需样式淡入淡出效果模块

    ¥swiper/scss/effect-fade - styles required for Fade Effect module

  • swiper/scss/effect-flip - 翻转效果模块所需样式

    ¥swiper/scss/effect-flip - styles required for Flip Effect module

  • swiper/scss/free-mode - 自由模式模块所需样式

    ¥swiper/scss/free-mode - styles required for Free Mode module

  • swiper/scss/grid - 网格模块所需样式

    ¥swiper/scss/grid - styles required for Grid module

  • swiper/scss/hash-navigation - 哈希导航模块所需样式

    ¥swiper/scss/hash-navigation - styles required for Hash Navigation module

  • swiper/scss/history - 历史记录模块所需样式

    ¥swiper/scss/history - styles required for History module

  • swiper/scss/keyboard - 键盘模块所需样式

    ¥swiper/scss/keyboard - styles required for Keyboard module

  • swiper/scss/manipulation - 操作模块所需样式

    ¥swiper/scss/manipulation - styles required for Manipulation module

  • swiper/scss/mousewheel - 鼠标滚轮模块所需样式

    ¥swiper/scss/mousewheel - styles required for Mousewheel module

  • swiper/scss/navigation - 导航模块所需样式

    ¥swiper/scss/navigation - styles required for Navigation module

  • swiper/scss/pagination - 分页模块所需样式

    ¥swiper/scss/pagination - styles required for Pagination module

  • swiper/scss/parallax - 视差模块所需样式

    ¥swiper/scss/parallax - styles required for Parallax module

  • swiper/scss/scrollbar - 滚动条模块所需样式

    ¥swiper/scss/scrollbar - styles required for Scrollbar module

  • swiper/scss/thumbs - 缩略图模块所需样式

    ¥swiper/scss/thumbs - styles required for Thumbs module

  • swiper/scss/virtual - 虚拟模块所需样式

    ¥swiper/scss/virtual - styles required for Virtual module

  • swiper/scss/zoom - 缩放模块所需样式

    ¥swiper/scss/zoom - styles required for Zoom module

初始化 Swiper

¥Initialize Swiper

现在,当我们有了 Swiper 的 HTML 代码后,我们需要使用以下函数初始化它:

¥Now, when we have Swiper's HTML, we need to initialize it using the following function:

new Swiper(swiperContainer, 参数) - 使用选项初始化 Swiper

¥new Swiper(swiperContainer, parameters)- initialize swiper with options

  • swiperContainer - Swiper 容器 HTML 元素的 HTML 元素或字符串(带有 CSS 选择器)。必需。

    ¥swiperContainer - HTMLElement or string (with CSS Selector) of swiper container HTML element. Required.

  • 参数 - object - 带有 Swiper 参数的对象。可选。

    ¥parameters - object - object with Swiper parameters. Optional.

  • 方法返回已初始化的 Swiper 实例

    ¥Method returns initialized Swiper instance

例如:

¥For example:

const swiper = new Swiper('.swiper', {
  speed: 400,
  spaceBetween: 100,
});

初始化 Swiper 后,可以通过其 HTMLElement 访问 Swiper 实例。它是 Swiper HTML 容器元素的 swiper 属性:

¥After you initialize Swiper it is possible to access to Swiper's instance on its HTMLElement. It is swiper property of Swiper's HTML container element:

const swiper = document.querySelector('.swiper').swiper;

// Now you can use all slider methods like
swiper.slideNext();

参数

¥Parameters

让我们来看看所有可用参数的列表:

¥Let's look on list of all available parameters:

NameTypeDefaultDescription
a11yany

Object with a11y parameters or boolean true to enable with default settings.

const swiper = new Swiper('.swiper', {
  a11y: {
    prevSlideMessage: 'Previous slide',
    nextSlideMessage: 'Next slide',
  },
});
allowSlideNextbooleantrue

Set to false to disable swiping to next slide direction (to right or bottom)

allowSlidePrevbooleantrue

Set to false to disable swiping to previous slide direction (to left or top)

allowTouchMovebooleantrue

If false, then the only way to switch the slide is use of external API functions like slidePrev or slideNext

autoHeightbooleanfalse

Set to true and slider wrapper will adapt its height to the height of the currently active slide

autoplayany

Object with autoplay parameters or boolean true to enable with default settings

const swiper = new Swiper('.swiper', {
 autoplay: {
   delay: 5000,
 },
});
breakpointsobject

Allows to set different parameter for different responsive breakpoints (screen sizes). Not all parameters can be changed in breakpoints, only those which do not require different layout and logic, like slidesPerView, slidesPerGroup, spaceBetween, grid.rows. Such parameters like loop and effect won't work

const swiper = new Swiper('.swiper', {
  // Default parameters
  slidesPerView: 1,
  spaceBetween: 10,
  // Responsive breakpoints
  breakpoints: {
    // when window width is >= 320px
    320: {
      slidesPerView: 2,
      spaceBetween: 20
    },
    // when window width is >= 480px
    480: {
      slidesPerView: 3,
      spaceBetween: 30
    },
    // when window width is >= 640px
    640: {
      slidesPerView: 4,
      spaceBetween: 40
    }
  }
})
const swiper = new Swiper('.swiper', {
  slidesPerView: 1,
  spaceBetween: 10,
  // using "ratio" endpoints
  breakpoints: {
    '@0.75': {
      slidesPerView: 2,
      spaceBetween: 20,
    },
    '@1.00': {
      slidesPerView: 3,
      spaceBetween: 40,
    },
    '@1.50': {
      slidesPerView: 4,
      spaceBetween: 50,
    },
  }
});
breakpointsBaseany'window'

Base for breakpoints (beta). Can be window or container. If set to window (by default) then breakpoint keys mean window width. If set to container then breakpoint keys treated as swiper container width

cardsEffectany

Object with Cards-effect parameters

const swiper = new Swiper('.swiper', {
  effect: 'cards',
  cardsEffect: {
    // ...
  },
});
centerInsufficientSlidesbooleanfalse

When enabled it center slides if the amount of slides less than slidesPerView. Not intended to be used loop mode and grid.rows

centeredSlidesbooleanfalse

If true, then active slide will be centered, not always on the left side.

centeredSlidesBoundsbooleanfalse

If true, then active slide will be centered without adding gaps at the beginning and end of slider. Required centeredSlides: true. Not intended to be used with loop or pagination

containerModifierClassstring'swiper-'

The beginning of the modifier CSS class that can be added to swiper container depending on different parameters

controllerany

Object with controller parameters or boolean true to enable with default settings

const swiper = new Swiper('.swiper', {
  controller: {
    inverse: true,
  },
});
coverflowEffectany

Object with Coverflow-effect parameters.

const swiper = new Swiper('.swiper', {
  effect: 'coverflow',
  coverflowEffect: {
    rotate: 30,
    slideShadows: false,
  },
});
createElementsbooleanfalse

When enabled Swiper will automatically wrap slides with swiper-wrapper element, and will create required elements for navigation, pagination and scrollbar they are enabled (with their respective params object or with boolean true))

creativeEffectany

Object with Creative-effect parameters

const swiper = new Swiper('.swiper', {
  effect: 'creative',
  creativeEffect: {
    prev: {
      // will set `translateZ(-400px)` on previous slides
      translate: [0, 0, -400],
    },
    next: {
      // will set `translateX(100%)` on next slides
      translate: ['100%', 0, 0],
    },
  },
});
cssModebooleanfalse

When enabled it will use modern CSS Scroll Snap API. It doesn't support all of Swiper's features, but potentially should bring a much better performance in simple configurations.

This is what is not supported when it is enabled:

  • Cube effect
  • speed parameter may not have no effect
  • All transition start/end related events (use slideChange instead)
  • slidesPerGroup has limited support
  • simulateTouch doesn't have effect and "dragging" with mouse doesn't work
  • resistance doesn't have any effect
  • allowSlidePrev/Next
  • swipeHandler

In case if you use it with other effects, especially 3D effects, it is required to wrap slide's content with <div className="swiper-slide-transform"> element. And if you use any custom styles on slides (like background colors, border radius, border, etc.), they should be set on swiper-slide-transform element instead.

<div class="swiper">
  <div class="swiper-wrapper">
    <div class="swiper-slide">
      <!-- wrap slide content with transform element -->
      <div class="swiper-slide-transform">
        ... slide content ...
      </div>
    </div>
    ...
  </div>
</div>
<script>
const swiper = new Swiper('.swiper', {
   effect: 'flip',
   cssMode: true,
 });
</script>
cubeEffectany

Object with Cube-effect parameters

const swiper = new Swiper('.swiper', {
  effect: 'cube',
  cubeEffect: {
    slideShadows: false,
  },
});
direction'horizontal' | 'vertical''horizontal'

Can be 'horizontal' or 'vertical' (for vertical slider).

edgeSwipeDetectionstring | booleanfalse

Enable to release Swiper events for swipe-back work in app. If set to 'prevent' then it will prevent system swipe-back navigation instead. This feature works only with "touch" events (and not pointer events), so it will work on iOS/Android devices and won't work on Windows devices with pointer (touch) events.

edgeSwipeThresholdnumber20

Area (in px) from left edge of the screen to release touch events for swipe-back in app

effectstring'slide'

Transition effect. Can be 'slide', 'fade', 'cube', 'coverflow', 'flip', 'creative' or 'cards'

enabledbooleantrue

Whether Swiper initially enabled. When Swiper is disabled, it will hide all navigation elements and won't respond to any events and interactions

eventsPrefixstring`swiper`

Event name prefix for all DOM events emitted by Swiper Element (web component)

fadeEffectany

Object with Fade-effect parameters

const swiper = new Swiper('.swiper', {
  effect: 'fade',
  fadeEffect: {
    crossFade: true
  },
});
flipEffectany

Object with Flip-effect parameters

const swiper = new Swiper('.swiper', {
  effect: 'flip',
  flipEffect: {
    slideShadows: false,
  },
});
focusableElementsstring'input, select, option, textarea, button, video, label'

CSS selector for focusable elements. Swiping will be disabled on such elements if they are "focused"

followFingerbooleantrue

If disabled, then slider will be animated only when you release it, it will not move while you hold your finger on it

freeModeany

Enables free mode functionality. Object with free mode parameters or boolean true to enable with default settings.

const swiper = new Swiper('.swiper', {
  freeMode: true,
});

const swiper = new Swiper('.swiper', {
  freeMode: {
    enabled: true,
    sticky: true,
  },
});
grabCursorbooleanfalse

This option may a little improve desktop usability. If true, user will see the "grab" cursor when hover on Swiper

gridany

Object with grid parameters to enable "multirow" slider.

const swiper = new Swiper('.swiper', {
  grid: {
    rows: 2,
  },
});
hashNavigationany

Enables hash url navigation to for slides. Object with hash navigation parameters or boolean true to enable with default settings

const swiper = new Swiper('.swiper', {
  hashNavigation: {
    replaceState: true,
  },
});
heightnull | numbernull

Swiper height (in px). Parameter allows to force Swiper height. Useful only if you initialize Swiper when it is hidden and in SSR and Test environments for correct Swiper initialization

Setting this parameter will make Swiper not responsive

historyany

Enables history push state where every slide will have its own url. In this parameter you have to specify main slides url like "slides" and specify every slide url using data-history attribute.

Object with history navigation parameters or boolean true to enable with default settings

const swiper = new Swiper('.swiper', {
  history: {
    replaceState: true,
  },
});
<!-- will produce "slides/slide1" url in browser history -->
<div class="swiper-slide" data-history="slide1"></div>
initbooleantrue

Whether Swiper should be initialised automatically when you create an instance. If disabled, then you need to init it manually by calling swiper.init()

initialSlidenumber0

Index number of initial slide.

injectStylesstring[]

Inject text styles to the shadow DOM. Only for usage with Swiper Element

injectStylesUrlsstring[]

Inject styles <link>s to the shadow DOM. Only for usage with Swiper Element

keyboardany

Enables navigation through slides using keyboard. Object with keyboard parameters or boolean true to enable with default settings

const swiper = new Swiper('.swiper', {
  keyboard: {
    enabled: true,
    onlyInViewport: false,
  },
});
lazyPreloadPrevNextnumber0

Number of next and previous slides to preload. Only applicable if using lazy loading.

lazyPreloaderClassstring'swiper-lazy-preloader'

CSS class name of lazy preloader

longSwipesbooleantrue

Set to false if you want to disable long swipes

longSwipesMsnumber300

Minimal duration (in ms) to trigger swipe to next/previous slide during long swipes

longSwipesRationumber0.5

Ratio to trigger swipe to next/previous slide during long swipes

loopbooleanfalse

Set to true to enable continuous loop mode

Because of nature of how the loop mode works (it will rearrange slides), total number of slides must be:

  • more than or equal to slidesPerView + slidesPerGroup
  • even to slidesPerGroup (or use loopAddBlankSlides parameter)
  • even to grid.rows (or use loopAddBlankSlides parameter)
loopAddBlankSlidesbooleantrue

Automatically adds blank slides if you use Grid or slidesPerGroup and the total amount of slides is not even to slidesPerGroup or to grid.rows

loopAdditionalSlidesnumber0

Allows to increase amount of looped slides

loopPreventsSlidingbooleantrue

If enabled then slideNext/Prev will do nothing while slider is animating in loop mode

maxBackfaceHiddenSlidesnumber10

If total number of slides less than specified here value, then Swiper will enable backface-visibility: hidden on slide elements to reduce visual "flicker" in Safari.

It is not recommended to enable it on large amount of slides as it will reduce performance

modulesany[]

Array with Swiper modules

import Swiper from 'swiper';
import { Navigation, Pagination } from 'swiper/modules';

const swiper = new Swiper('.swiper', {
   modules: [ Navigation, Pagination ],
 });
mousewheelany

Enables navigation through slides using mouse wheel. Object with mousewheel parameters or boolean true to enable with default settings

const swiper = new Swiper('.swiper', {
  mousewheel: {
    invert: true,
  },
});
navigationany

Object with navigation parameters or boolean true to enable with default settings.

const swiper = new Swiper('.swiper', {
  navigation: {
    nextEl: '.swiper-button-next',
    prevEl: '.swiper-button-prev',
  },
});
nestedbooleanfalse

Set to true on Swiper for correct touch events interception. Use only on swipers that use same direction as the parent one

noSwipingbooleantrue

Enable/disable swiping on elements matched to class specified in noSwipingClass

noSwipingClassstring'swiper-no-swiping'

Specify noSwiping's element css class

noSwipingSelectorstring

Can be used instead of noSwipingClass to specify elements to disable swiping on. For example 'input' will disable swiping on all inputs

normalizeSlideIndexbooleantrue

Normalize slide index.

observeParentsbooleanfalse

Set to true if you also need to watch Mutations for Swiper parent elements

observeSlideChildrenbooleanfalse

Set to true if you also need to watch Mutations for Swiper slide children elements

observerbooleanfalse

Set to true to enable Mutation Observer on Swiper and its elements. In this case Swiper will be updated (reinitialized) each time if you change its style (like hide/show) or modify its child elements (like adding/removing slides)

onobject

Register event handlers

onAnyfunction(handler)

Add event listener that will be fired on all events

const swiper = new Swiper('.swiper', {
   onAny(eventName, ...args) {
     console.log('Event: ', eventName);
     console.log('Event data: ', args);
   }
 });
oneWayMovementbooleanfalse

When enabled, will swipe slides only forward (one-way) regardless of swipe direction

paginationany

Object with pagination parameters or boolean true to enable with default settings.

const swiper = new Swiper('.swiper', {
  pagination: {
    el: '.swiper-pagination',
    type: 'bullets',
  },
});
parallaxany

Object with parallax parameters or boolean true to enable with default settings.

const swiper = new Swiper('.swiper', {
  parallax: true,
});
passiveListenersbooleantrue

Passive event listeners will be used by default where possible to improve scrolling performance on mobile devices. But if you need to use e.preventDefault and you have conflict with it, then you should disable this parameter

preventClicksbooleantrue

Set to true to prevent accidental unwanted clicks on links during swiping

preventClicksPropagationbooleantrue

Set to true to stop clicks event propagation on links during swiping

preventInteractionOnTransitionbooleanfalse

When enabled it won't allow to change slides by swiping or navigation/pagination buttons during transition

resistancebooleantrue

Set to false if you want to disable resistant bounds

resistanceRationumber0.85

This option allows you to control resistance ratio

resizeObserverbooleantrue

When enabled it will use ResizeObserver (if supported by browser) on swiper container to detect container resize (instead of watching for window resize)

rewindbooleanfalse

Set to true to enable "rewind" mode. When enabled, clicking "next" navigation button (or calling .slideNext()) when on last slide will slide back to the first slide. Clicking "prev" navigation button (or calling .slidePrev()) when on first slide will slide forward to the last slide.

Should not be used together with loop mode

roundLengthsbooleanfalse

Set to true to round values of slides width and height to prevent blurry texts on usual resolution screens (if you have such)

runCallbacksOnInitbooleantrue

Fire Transition/SlideChange/Start/End events on swiper initialization. Such events will be fired on initialization in case of your initialSlide is not 0, or you use loop mode

scrollbarany

Object with scrollbar parameters or boolean true to enable with default settings.

const swiper = new Swiper('.swiper', {
  scrollbar: {
    el: '.swiper-scrollbar',
    draggable: true,
  },
});
setWrapperSizebooleanfalse

Enabled this option and plugin will set width/height on swiper wrapper equal to total size of all slides. Mostly should be used as compatibility fallback option for browser that don't support flexbox layout well

shortSwipesbooleantrue

Set to false if you want to disable short swipes

simulateTouchbooleantrue

If true, Swiper will accept mouse events like touch events (click and drag to change slides)

slideActiveClassstring'swiper-slide-active'

CSS class name of currently active slide

By changing classes you will also need to change Swiper's CSS to reflect changed classes

Not supported in Swiper React/Vue components

slideBlankClassstring'swiper-slide-blank'

CSS class name of the blank slide added by the loop mode (when loopAddBlankSlides is enabled)

Not supported in Swiper React/Vue

slideClassstring'swiper-slide'

CSS class name of slide

By changing classes you will also need to change Swiper's CSS to reflect changed classes

Not supported in Swiper React/Vue components

slideFullyVisibleClassstring'swiper-slide-fully-visible'

CSS class name of fully (when whole slide is in the viewport) visible slide

Not supported in Swiper React/Vue

slideNextClassstring'swiper-slide-next'

CSS class name of slide which is right after currently active slide

By changing classes you will also need to change Swiper's CSS to reflect changed classes

Not supported in Swiper React/Vue

slidePrevClassstring'swiper-slide-prev'

CSS class name of slide which is right before currently active slide

By changing classes you will also need to change Swiper's CSS to reflect changed classes

Not supported in Swiper React/Vue

slideToClickedSlidebooleanfalse

Set to true and click on any slide will produce transition to this slide

slideVisibleClassstring'swiper-slide-visible'

CSS class name of currently/partially visible slide

By changing classes you will also need to change Swiper's CSS to reflect changed classes

Not supported in Swiper React/Vue

slidesOffsetAfternumber0

Add (in px) additional slide offset in the end of the container (after all slides)

slidesOffsetBeforenumber0

Add (in px) additional slide offset in the beginning of the container (before all slides)

slidesPerGroupnumber1

Set numbers of slides to define and enable group sliding. Useful to use with slidesPerView > 1

slidesPerGroupAutobooleanfalse

This param intended to be used only with slidesPerView: 'auto' and slidesPerGroup: 1. When enabled, it will skip all slides in view on .slideNext() & .slidePrev() methods calls, on Navigation "buttons" clicks and in autoplay.

slidesPerGroupSkipnumber0

The parameter works in the following way: If slidesPerGroupSkip equals 0 (default), no slides are excluded from grouping, and the resulting behaviour is the same as without this change.

If slidesPerGroupSkip is equal or greater than 1 the first X slides are treated as single groups, whereas all following slides are grouped by the slidesPerGroup value.

slidesPerViewnumber | 'auto'1

Number of slides per view (slides visible at the same time on slider's container).

slidesPerView: 'auto' is currently not compatible with multirow mode, when grid.rows > 1

spaceBetweenstring | number0

Distance between slides in px.

If you use "margin" css property to the elements which go into Swiper in which you pass "spaceBetween" into, navigation might not work properly.

speednumber300

Duration of transition between slides (in ms)

swipeHandleranynull

String with CSS selector or HTML element of the container with pagination that will work as only available handler for swiping

swiperElementNodeNamestring'SWIPER-CONTAINER'

The name of the swiper element node name; used for detecting web component rendering

thresholdnumber5

Threshold value in px. If "touch distance" will be lower than this value then swiper will not move

thumbsany

Object with thumbs component parameters

const swiper = new Swiper('.swiper', {
  ...
  thumbs: {
    swiper: thumbsSwiper
  }
});
touchAnglenumber45

Allowable angle (in degrees) to trigger touch move

touchEventsTarget'container' | 'wrapper''wrapper'

Target element to listen touch events on. Can be 'container' (to listen for touch events on swiper) or 'wrapper'(to listen for touch events on swiper-wrapper)

touchMoveStopPropagationbooleanfalse

If enabled, then propagation of "touchmove" will be stopped

touchRationumber1

Touch ratio

touchReleaseOnEdgesbooleanfalse

Enable to release touch events on slider edge position (beginning, end) to allow for further page scrolling. This feature works only with "touch" events (and not pointer events), so it will work on iOS/Android devices and won't work on Windows devices with pointer events. Also threshold parameter must be set to 0

touchStartForcePreventDefaultbooleanfalse

Force to always prevent default for touchstart (pointerdown) event

touchStartPreventDefaultbooleantrue

If disabled, pointerdown event won't be prevented

uniqueNavElementsbooleantrue

If enabled (by default) and navigation elements' parameters passed as a string (like ".pagination") then Swiper will look for such elements through child elements first. Applies for pagination, prev/next buttons and scrollbar elements

updateOnWindowResizebooleantrue

Swiper will recalculate slides position on window resize (orientationchange)

urlnull | stringnull

Required for active slide detection when rendered on server-side and enabled history

userAgentnull | stringnull

userAgent string. Required for browser/device detection when rendered on server-side

virtualany

Enables virtual slides functionality. Object with virtual slides parameters or boolean true to enable with default settings.

const swiper = new Swiper('.swiper', {
  virtual: {
    slides: ['Slide 1', 'Slide 2', 'Slide 3', 'Slide 4', 'Slide 5'],
  },
});
virtualTranslatebooleanfalse

Enabled this option and swiper will be operated as usual except it will not move, real translate values on wrapper will not be set. Useful when you may need to create custom slide transition

watchOverflowbooleantrue

When enabled Swiper will be disabled and hide navigation buttons on case there are not enough slides for sliding.

watchSlidesProgressbooleanfalse

Enable this feature to calculate each slides progress and visibility (slides in viewport will have additional visible class)

widthnull | numbernull

Swiper width (in px). Parameter allows to force Swiper width. Useful only if you initialize Swiper when it is hidden and in SSR and Test environments for correct Swiper initialization

Setting this parameter will make Swiper not responsive

wrapperClassstring'swiper-wrapper'

CSS class name of slides' wrapper

By changing classes you will also need to change Swiper's CSS to reflect changed classes

Not supported in Swiper React/Vue

zoomany

Enables zooming functionality. Object with zoom parameters or boolean true to enable with default settings

const swiper = new Swiper('.swiper', {
  zoom: {
    maxRatio: 5,
  },
});

方法和属性

¥Methods & Properties

初始化滑块后,我们在变量中保存了它的初始化实例(如上例中的 swiper 变量),其中包含有用的方法和属性:

¥After we initialize Slider we have its initialized instance in variable (like swiper variable in example above) with helpful methods and properties:

Properties
swiper.a11yany
swiper.activeIndexnumber

Index number of currently active slide

Note, that in loop mode active index value will be always shifted on a number of looped slides

swiper.allowSlideNextboolean

Disable / enable ability to slide to the next slides by assigning false / true to this property

swiper.allowSlidePrevboolean

Disable / enable ability to slide to the previous slides by assigning false / true to this property

swiper.allowTouchMoveboolean

Disable / enable ability move slider by grabbing it with mouse or by touching it with finger (on touch screens) by assigning false / true to this property

swiper.animatingboolean

true if swiper is in transition

swiper.autoplayany
swiper.cardsEffectany
swiper.clickedIndexnumber

Index number of last clicked slide

swiper.clickedSlideHTMLElement

Link to last clicked slide (HTMLElement)

swiper.controllerany
swiper.coverflowEffectany
swiper.creativeEffectany
swiper.cubeEffectany
swiper.defaultsany

Swiper default options

swiper.elHTMLElement

Slider container HTML element

swiper.extendedDefaultsany

Object with global Swiper extended options

swiper.fadeEffectany
swiper.flipEffectany
swiper.freeModeany
swiper.hashNavigationany
swiper.heightnumber

Height of container

swiper.historyany
swiper.isBeginningboolean

true if slider on most "left"/"top" position

swiper.isEndboolean

true if slider on most "right"/"bottom" position

swiper.isLockedboolean

true if slide is "locked" (by watchOverflow) and slides can not be, e.g. when amount of slides is less that slides per view

swiper.keyboardany
swiper.mousewheelany
swiper.navigationany
swiper.originalParamsany

Object with original initialization parameters

swiper.paginationany
swiper.parallaxany
swiper.paramsany

Object with passed initialization parameters

swiper.previousIndexnumber

Index number of previously active slide

swiper.progressnumber

Current progress of wrapper translate (from 0 to 1)

swiper.realIndexnumber

Index number of currently active slide considering rearranged slides in loop mode

swiper.scrollbarany
swiper.slidesHTMLElement[]

Array of slides HTML elements. To get specific slide HTMLElement use swiper.slides[1]

swiper.slidesElHTMLElement

Wrapper HTML element

swiper.slidesGridnumber[]

Slides grid

swiper.slidesSizesGridnumber[]

Array of widths for slides

swiper.snapGridnumber[]

Slides snap grid

swiper.snapIndexnumber

Index number of current snap in snapGrid

swiper.swipeDirection'prev' | 'next'

Direction of sliding

swiper.thumbsany
swiper.touchesobject

Object with the following touch event properties:

  • swiper.touches.startX
  • swiper.touches.startY
  • swiper.touches.currentX
  • swiper.touches.currentY
  • swiper.touches.diff
swiper.translatenumber

Current value of wrapper translate

swiper.virtualany
swiper.widthnumber

Width of container

swiper.wrapperElHTMLElement

Wrapper HTML element

swiper.zoomany
Methods
swiper.attachEvents()

Attach all events listeners again

swiper.changeDirection(direction, needUpdate)

Changes slider direction from horizontal to vertical and back.

  • direction - 'horizontal' | 'vertical' - New direction. If not specified, then will automatically changed to opposite direction
  • needUpdate - boolean - Will call swiper.update(). Default true
swiper.changeLanguageDirection(direction)

Changes slider language

  • direction - 'rtl' | 'ltr' - New direction. Should be `rtl` or `ltr`
swiper.destroy(deleteInstance, cleanStyles)

Destroy slider instance and detach all events listeners

  • deleteInstance - boolean - Set it to false (by default it is true) to not to delete Swiper instance
  • cleanStyles - boolean - Set it to true (by default it is true) and all custom styles will be removed from slides, wrapper and container. Useful if you need to destroy Swiper and to init again with new options or in different direction
swiper.detachEvents()

Detach all events listeners

swiper.disable()

Disable Swiper (if it was enabled). When Swiper is disabled, it will hide all navigation elements and won't respond to any events and interactions

swiper.emit(event, args)

Fire event on instance

swiper.enable()

Enable Swiper (if it was disabled)

swiper.extendDefaults(options)

Extend global Swiper defaults

swiper.getTranslate()

Get current value of swiper wrapper css3 transform translate

swiper.init(el)

Initialize slider

swiper.maxTranslate()

Get current maximal translate value

swiper.minTranslate()

Get current minimal translate value

swiper.off(event, handler)

Remove event handler

swiper.offAny(handler)

Remove event listener that will be fired on all events

swiper.on(event, handler)

Add event handler

swiper.onAny(handler)

Add event listener that will be fired on all events

swiper.once(event, handler)

Add event handler that will be removed after it was fired

swiper.setGrabCursor()

Set grab cursor

swiper.setProgress(progress, speed)

Set Swiper translate progress (from 0 to 1). Where 0 - its initial position (offset) on first slide, and 1 - its maximum position (offset) on last slide

  • progress - number - Swiper translate progress (from 0 to 1).
  • speed - number - Transition duration (in ms).
swiper.setTranslate(translate)

Set custom css3 transform's translate value for swiper wrapper

swiper.slideNext(speed, runCallbacks)

Run transition to next slide.

  • speed - number - Transition duration (in ms).
  • runCallbacks - boolean - Set it to false (by default it is true) and transition will not produce transition events.
swiper.slidePrev(speed, runCallbacks)

Run transition to previous slide.

  • speed - number - Transition duration (in ms).
  • runCallbacks - boolean - Set it to false (by default it is true) and transition will not produce transition events.
swiper.slideReset(speed, runCallbacks)

Reset swiper position to currently active slide for the duration equal to 'speed' parameter.

  • speed - number - Transition duration (in ms).
  • runCallbacks - boolean - Set it to false (by default it is true) and transition will not produce transition events.
swiper.slideTo(index, speed, runCallbacks)

Run transition to the slide with index number equal to 'index' parameter for the duration equal to 'speed' parameter.

  • index - number - Index number of slide.
  • speed - number - Transition duration (in ms).
  • runCallbacks - boolean - Set it to false (by default it is true) and transition will not produce transition events.
swiper.slideToClosest(speed, runCallbacks)

Reset swiper position to closest slide/snap point for the duration equal to 'speed' parameter.

  • speed - number - Transition duration (in ms).
  • runCallbacks - boolean - Set it to false (by default it is true) and transition will not produce transition events.
swiper.slideToLoop(index, speed, runCallbacks)

Does the same as .slideTo but for the case when used with enabled loop. So this method will slide to slides with realIndex matching to passed index

  • index - number - Index number of slide.
  • speed - number - Transition duration (in ms).
  • runCallbacks - boolean - Set it to false (by default it is true) and transition will not produce transition events.
swiper.slidesPerViewDynamic()

Get dynamically calculated amount of slides per view, useful only when slidesPerView set to auto

swiper.translateTo(translate, speed, runCallbacks, translateBounds)

Animate custom css3 transform's translate value for swiper wrapper

  • translate - number - Translate value (in px)
  • speed - number - Transition duration (in ms)
  • runCallbacks - boolean - Set it to false (by default it is true) and transition will not produce transition events
  • translateBounds - boolean - Set it to false (by default it is true) and transition value can extend beyond min and max translate
swiper.unsetGrabCursor()

Unset grab cursor

swiper.update()

You should call it after you add/remove slides manually, or after you hide/show it, or do any custom DOM modifications with Swiper This method also includes subcall of the following methods which you can use separately:

swiper.updateAutoHeight(speed)

Force swiper to update its height (when autoHeight enabled) for the duration equal to 'speed' parameter

  • speed - number - Transition duration (in ms).
swiper.updateProgress()

recalculate swiper progress

swiper.updateSize()

recalculate size of swiper container

swiper.updateSlides()

recalculate number of slides and their offsets. Useful after you add/remove slides with JavaScript

swiper.updateSlidesClasses()

update active/prev/next classes on slides and bullets

swiper.use(modules)

Installs modules on Swiper in runtime.

事件

¥Events

Swiper 附带一系列可供监听的实用事件。事件可以通过两种方式分配:

¥Swiper comes with a bunch of useful events you can listen. Events can be assigned in two ways:

  1. 在滑动条初始化时使用 on 参数:

    ¥Using on parameter on swiper initialization:

    const swiper = new Swiper('.swiper', {
      // ...
      on: {
        init: function () {
          console.log('swiper initialized');
        },
      },
    });
    
  2. 在滑动条初始化后使用 on 方法。

    ¥Using on method after swiper initialization.

    const swiper = new Swiper('.swiper', {
      // ...
    });
    swiper.on('slideChange', function () {
      console.log('slide changed');
    });
    
Please note, that this keyword within event handler always points to Swiper instance
NameArgumentsDescription
activeIndexChange(swiper)

Event will fired on active index change

afterInit(swiper)

Event will fired right after initialization

beforeDestroy(swiper)

Event will be fired right before Swiper destroyed

beforeInit(swiper)

Event will fired right before initialization

beforeLoopFix(swiper)

Event will be fired right before "loop fix"

beforeResize(swiper)

Event will fired before resize handler

beforeSlideChangeStart(swiper)

Event will fired before slide change transition start

beforeTransitionStart(swiper, speed, internal)

Event will fired before transition start

breakpoint(swiper, breakpointParams)

Event will be fired on breakpoint change

changeDirection(swiper)

Event will fired on direction change

click(swiper, event)

Event will be fired when user click/tap on Swiper. Receives pointerup event as an arguments.

destroy(swiper)

Event will be fired on swiper destroy

doubleClick(swiper, event)

Event will be fired when user double click/tap on Swiper

doubleTap(swiper, event)

Event will be fired when user double tap on Swiper's container. Receives pointerup event as an arguments

fromEdge(swiper)

Event will be fired when Swiper goes from beginning or end position

init(swiper)

Fired right after Swiper initialization.

Note that with swiper.on('init') syntax it will work only in case you set init: false parameter.

const swiper = new Swiper('.swiper', {
  init: false,
  // other parameters
});
swiper.on('init', function() {
 // do something
});
// init Swiper
swiper.init();
// Otherwise use it as the parameter:
const swiper = new Swiper('.swiper', {
  // other parameters
  on: {
    init: function () {
      // do something
    },
  }
});
lock(swiper)

Event will be fired when swiper is locked (when watchOverflow enabled)

loopFix(swiper)

Event will be fired after "loop fix"

momentumBounce(swiper)

Event will be fired on momentum bounce

observerUpdate(swiper)

Event will be fired if observer is enabled and it detects DOM mutations

orientationchange(swiper)

Event will be fired on orientation change (e.g. landscape -> portrait)

progress(swiper, progress)

Event will be fired when Swiper progress is changed, as an arguments it receives progress that is always from 0 to 1

reachBeginning(swiper)

Event will be fired when Swiper reach its beginning (initial position)

reachEnd(swiper)

Event will be fired when Swiper reach last slide

realIndexChange(swiper)

Event will fired on real index change

resize(swiper)

Event will be fired on window resize right before swiper's onresize manipulation

setTransition(swiper, transition)

Event will be fired everytime when swiper starts animation. Receives current transition duration (in ms) as an arguments

setTranslate(swiper, translate)

Event will be fired when swiper's wrapper change its position. Receives current translate value as an arguments

slideChange(swiper)

Event will be fired when currently active slide is changed

slideChangeTransitionEnd(swiper)

Event will be fired after animation to other slide (next or previous).

slideChangeTransitionStart(swiper)

Event will be fired in the beginning of animation to other slide (next or previous).

slideNextTransitionEnd(swiper)

Same as "slideChangeTransitionEnd" but for "forward" direction only

slideNextTransitionStart(swiper)

Same as "slideChangeTransitionStart" but for "forward" direction only

slidePrevTransitionEnd(swiper)

Same as "slideChangeTransitionEnd" but for "backward" direction only

slidePrevTransitionStart(swiper)

Same as "slideChangeTransitionStart" but for "backward" direction only

slideResetTransitionEnd(swiper)

Event will be fired in the end of animation of resetting slide to current one

slideResetTransitionStart(swiper)

Event will be fired in the beginning of animation of resetting slide to current one

sliderFirstMove(swiper, event)

Event will be fired with first touch/drag move

sliderMove(swiper, event)

Event will be fired when user touch and move finger over Swiper and move it. Receives pointermove event as an arguments.

slidesGridLengthChange(swiper)

Event will be fired when slides grid has changed

slidesLengthChange(swiper)

Event will be fired when number of slides has changed

slidesUpdated(swiper)

Event will be fired after slides and their sizes are calculated and updated

snapGridLengthChange(swiper)

Event will be fired when snap grid has changed

snapIndexChange(swiper)

Event will fired on snap index change

tap(swiper, event)

Event will be fired when user click/tap on Swiper. Receives pointerup event as an arguments.

toEdge(swiper)

Event will be fired when Swiper goes to beginning or end position

touchEnd(swiper, event)

Event will be fired when user release Swiper. Receives pointerup event as an arguments.

touchMove(swiper, event)

Event will be fired when user touch and move finger over Swiper. Receives pointermove event as an arguments.

touchMoveOpposite(swiper, event)

Event will be fired when user touch and move finger over Swiper in direction opposite to direction parameter. Receives pointermove event as an arguments.

touchStart(swiper, event)

Event will be fired when user touch Swiper. Receives pointerdown event as an arguments.

transitionEnd(swiper)

Event will be fired after transition.

transitionStart(swiper)

Event will be fired in the beginning of transition.

unlock(swiper)

Event will be fired when swiper is unlocked (when watchOverflow enabled)

update(swiper)

Event will be fired after swiper.update() call

模块

¥Modules

导航参数

¥Navigation Parameters

NameTypeDefaultDescription
disabledClassstring'swiper-button-disabled'

CSS class name added to navigation button when it becomes disabled

enabledboolean

Boolean property to use with breakpoints to enable/disable navigation on certain breakpoints

hiddenClassstring'swiper-button-hidden'

CSS class name added to navigation button when it becomes hidden

hideOnClickbooleanfalse

Toggle navigation buttons visibility after click on Slider's container

lockClassstring'swiper-button-lock'

CSS class name added to navigation button when it is disabled

navigationDisabledClassstring'swiper-navigation-disabled'

CSS class name added on swiper container when navigation is disabled by breakpoint

nextElanynull

String with CSS selector or HTML element of the element that will work like "next" button after click on it

prevElanynull

String with CSS selector or HTML element of the element that will work like "prev" button after click on it

导航方法

¥Navigation Methods

Properties
swiper.nextElHTMLElement

HTMLElement of "next" navigation button

swiper.prevElHTMLElement

HTMLElement of "previous" navigation button

Methods
swiper.destroy()

Destroy navigation

swiper.init()

Initialize navigation

swiper.update()

Update navigation buttons state (enabled/disabled)

导航事件

¥Navigation Events

NameArgumentsDescription
navigationHide(swiper)

Event will be fired on navigation hide

navigationNext(swiper)

Event will be fired on navigation next button click

navigationPrev(swiper)

Event will be fired on navigation prev button click

navigationShow(swiper)

Event will be fired on navigation show

导航 CSS 自定义属性

¥Navigation CSS Custom Properties

 {
  --swiper-navigation-size: 44px;
  --swiper-navigation-top-offset: 50%;
  --swiper-navigation-sides-offset: 10px;
  --swiper-navigation-color: var(--swiper-theme-color);
}

Pagination

分页参数

¥Pagination Parameters

NameTypeDefaultDescription
bulletActiveClassstring'swiper-pagination-bullet-active'

CSS class name of currently active pagination bullet

bulletClassstring'swiper-pagination-bullet'

CSS class name of single pagination bullet

bulletElementstring'span'

Defines which HTML tag will be used to represent single pagination bullet. Only for 'bullets' pagination type.

clickablebooleanfalse

If true then clicking on pagination button will cause transition to appropriate slide. Only for bullets pagination type

clickableClassstring'swiper-pagination-clickable'

CSS class name set to pagination when it is clickable

currentClassstring'swiper-pagination-current'

CSS class name of the element with currently active index in "fraction" pagination

dynamicBulletsbooleanfalse

Good to enable if you use bullets pagination with a lot of slides. So it will keep only few bullets visible at the same time.

dynamicMainBulletsnumber1

The number of main bullets visible when dynamicBullets enabled.

elanynull

String with CSS selector or HTML element of the container with pagination

enabledboolean

Boolean property to use with breakpoints to enable/disable pagination on certain breakpoints

formatFractionCurrentfunction(number)

format fraction pagination current number. Function receives current number, and you need to return formatted value

formatFractionTotalfunction(number)

format fraction pagination total number. Function receives total number, and you need to return formatted value

hiddenClassstring'swiper-pagination-hidden'

CSS class name of pagination when it becomes inactive

hideOnClickbooleantrue

Toggle (hide/show) pagination container visibility after click on Slider's container

horizontalClassstring'swiper-pagination-horizontal'

CSS class name set to pagination in horizontal Swiper

lockClassstring'swiper-pagination-lock'

CSS class name set to pagination when it is disabled

modifierClassstring'swiper-pagination-'

The beginning of the modifier CSS class name that will be added to pagination depending on parameters

paginationDisabledClassstring'swiper-pagination-disabled'

CSS class name added on swiper container and pagination element when pagination is disabled by breakpoint

progressbarFillClassstring'swiper-pagination-progressbar-fill'

CSS class name of pagination progressbar fill element

progressbarOppositebooleanfalse

Makes pagination progressbar opposite to Swiper's direction parameter, means vertical progressbar for horizontal swiper direction and horizontal progressbar for vertical swiper direction

progressbarOppositeClassstring'swiper-pagination-progressbar-opposite'

CSS class name of pagination progressbar opposite

renderBulletfunction(index, className)

This parameter allows totally customize pagination bullets, you need to pass here a function that accepts index number of pagination bullet and required element class name (className). Only for 'bullets' pagination type

const swiper = new Swiper('.swiper', {
  //...
  pagination: {
    //...
    renderBullet: function (index, className) {
      return '<span class="' + className + '">' + (index + 1) + '</span>';
    },
  },
});
renderCustomfunction(swiper, current, total)

This parameter is required for 'custom' pagination type where you have to specify how it should be rendered.

const swiper = new Swiper('.swiper', {
  //...
  pagination: {
    //...
    renderCustom: function (swiper, current, total) {
      return current + ' of ' + total;
    },
  },
});
renderFractionfunction(currentClass, totalClass)

This parameter allows to customize "fraction" pagination html. Only for 'fraction' pagination type

const swiper = new Swiper('.swiper', {
  //...
  pagination: {
    //...
    renderFraction: function (currentClass, totalClass) {
      return '<span class="' + currentClass + '"></span>' +
              ' of ' +
              '<span class="' + totalClass + '"></span>';
    },
  },
});
renderProgressbarfunction(progressbarFillClass)

This parameter allows to customize "progress" pagination. Only for 'progress' pagination type

const swiper = new Swiper('.swiper', {
  //...
  pagination: {
    //...
    renderProgressbar: function (progressbarFillClass) {
      return '<span class="' + progressbarFillClass + '"></span>';
    },
  },
});
totalClassstring'swiper-pagination-total'

CSS class name of the element with total number of "snaps" in "fraction" pagination

type'progressbar' | 'bullets' | 'fraction' | 'custom''bullets'

String with type of pagination. Can be 'bullets', 'fraction', 'progressbar' or 'custom'

verticalClassstring'swiper-pagination-vertical'

CSS class name set to pagination in vertical Swiper

分页方法

¥Pagination Methods

Properties
swiper.bulletsHTMLElement[]

Array of pagination bullets HTML elements. To get specific slide HTMLElement use swiper.pagination.bullets[1].

swiper.elHTMLElement

HTMLElement of pagination container element

Methods
swiper.destroy()

Destroy pagination

swiper.init()

Initialize pagination

swiper.render()

Render pagination layout

swiper.update()

Update pagination state (enabled/disabled/active)

分页事件

¥Pagination Events

NameArgumentsDescription
paginationHide(swiper)

Event will be fired on pagination hide

paginationRender(swiper, paginationEl)

Event will be fired after pagination rendered

paginationShow(swiper)

Event will be fired on pagination show

paginationUpdate(swiper, paginationEl)

Event will be fired when pagination updated

分页 CSS 自定义属性

¥Pagination CSS Custom Properties

 {
  --swiper-pagination-color: var(--swiper-theme-color);
  --swiper-pagination-left: auto;
  --swiper-pagination-right: 8px;
  --swiper-pagination-bottom: 8px;
  --swiper-pagination-top: auto;
  --swiper-pagination-fraction-color: inherit;
  --swiper-pagination-progressbar-bg-color: rgba(0, 0, 0, 0.25);
  --swiper-pagination-progressbar-size: 4px;
  --swiper-pagination-bullet-size: 8px;
  --swiper-pagination-bullet-width: 8px;
  --swiper-pagination-bullet-height: 8px;
  --swiper-pagination-bullet-inactive-color: #000;
  --swiper-pagination-bullet-inactive-opacity: 0.2;
  --swiper-pagination-bullet-opacity: 1;
  --swiper-pagination-bullet-horizontal-gap: 4px;
  --swiper-pagination-bullet-vertical-gap: 6px;
}

Scrollbar

滚动条参数

¥Scrollbar Parameters

NameTypeDefaultDescription
dragClassstring'swiper-scrollbar-drag'

Scrollbar draggable element CSS class

dragSizenumber | 'auto''auto'

Size of scrollbar draggable element in px

draggablebooleanfalse

Set to true to enable make scrollbar draggable that allows you to control slider position

elanynull

String with CSS selector or HTML element of the container with scrollbar.

enabledboolean

Boolean property to use with breakpoints to enable/disable scrollbar on certain breakpoints

hidebooleantrue

Hide scrollbar automatically after user interaction

horizontalClassstring'swiper-scrollbar-horizontal'

CSS class name set to scrollbar in horizontal Swiper

lockClassstring'swiper-scrollbar-lock'

Scrollbar element additional CSS class when it is disabled

scrollbarDisabledClassstring'swiper-scrollbar-disabled'

CSS class name added on swiper container and scrollbar element when scrollbar is disabled by breakpoint

snapOnReleasebooleanfalse

Set to true to snap slider position to slides when you release scrollbar

verticalClassstring'swiper-scrollbar-vertical'

CSS class name set to scrollbar in vertical Swiper

滚动条方法

¥Scrollbar Methods

Properties
swiper.dragElHTMLElement

HTMLElement of Scrollbar draggable handler element

swiper.elHTMLElement

HTMLElement of Scrollbar container element

Methods
swiper.destroy()

Destroy scrollbar

swiper.init()

Initialize scrollbar

swiper.setTranslate()

Updates scrollbar translate

swiper.updateSize()

Updates scrollbar track and handler sizes

滚动条事件

¥Scrollbar Events

NameArgumentsDescription
scrollbarDragEnd(swiper, event)

Event will be fired on draggable scrollbar drag end

scrollbarDragMove(swiper, event)

Event will be fired on draggable scrollbar drag move

scrollbarDragStart(swiper, event)

Event will be fired on draggable scrollbar drag start

滚动条 CSS 自定义属性

¥Scrollbar CSS Custom Properties

 {
  --swiper-scrollbar-border-radius: 10px;
  --swiper-scrollbar-top: auto;
  --swiper-scrollbar-bottom: 4px;
  --swiper-scrollbar-left: auto;
  --swiper-scrollbar-right: 4px;
  --swiper-scrollbar-sides-offset: 1%;
  --swiper-scrollbar-bg-color: rgba(0, 0, 0, 0.1);
  --swiper-scrollbar-drag-bg-color: rgba(0, 0, 0, 0.5);
  --swiper-scrollbar-size: 4px;
}

Autoplay

自动播放参数

¥Autoplay Parameters

NameTypeDefaultDescription
delaynumber3000

Delay between transitions (in ms). If this parameter is not specified, auto play will be disabled

If you need to specify different delay for specific slides you can do it by usingdata-swiper-autoplay (in ms) attribute on slide.

<!-- hold this slide for 2 seconds -->
<div class="swiper-slide" data-swiper-autoplay="2000">
disableOnInteractionbooleantrue

Set to false and autoplay will not be disabled after user interactions (swipes), it will be restarted every time after interaction

pauseOnMouseEnterbooleanfalse

When enabled autoplay will be paused on pointer (mouse) enter over Swiper container.

reverseDirectionbooleanfalse

Enables autoplay in reverse direction

stopOnLastSlidebooleanfalse

Enable this parameter and autoplay will be stopped when it reaches last slide (has no effect in loop mode)

waitForTransitionbooleantrue

When enabled autoplay will wait for wrapper transition to continue. Can be disabled in case of using Virtual Translate when your slider may not have transition

自动播放方法

¥Autoplay Methods

Properties
swiper.pausedboolean

Whether autoplay is paused

swiper.runningboolean

Whether autoplay enabled and running

swiper.timeLeftnumber

If autoplay is paused, it contains time left (in ms) before transition to next slide

Methods
swiper.pause()

Pause autoplay

swiper.resume()

Resume autoplay

swiper.start()

Start autoplay

swiper.stop()

Stop autoplay

自动播放事件

¥Autoplay Events

NameArgumentsDescription
autoplay(swiper)

Event will be fired when slide changed with autoplay

autoplayPause(swiper)

Event will be fired on autoplay pause

autoplayResume(swiper)

Event will be fired on autoplay resume

autoplayStart(swiper)

Event will be fired in when autoplay started

autoplayStop(swiper)

Event will be fired when autoplay stopped

autoplayTimeLeft(swiper, timeLeft, percentage)

Event triggers continuously while autoplay is enabled. It contains time left (in ms) before transition to next slide and percentage of that time related to autoplay delay

Free Mode

自由模式参数

¥Free Mode Parameters

NameTypeDefaultDescription
enabledbooleanfalse

Whether the free mode is enabled

minimumVelocitynumber0.02

Minimum touchmove-velocity required to trigger free mode momentum

momentumbooleantrue

If enabled, then slide will keep moving for a while after you release it

momentumBouncebooleantrue

Set to false if you want to disable momentum bounce in free mode

momentumBounceRationumber1

Higher value produces larger momentum bounce effect

momentumRationumber1

Higher value produces larger momentum distance after you release slider

momentumVelocityRationumber1

Higher value produces larger momentum velocity after you release slider

stickybooleanfalse

Set to enabled to enable snap to slides positions in free mode

Grid

网格参数

¥Grid Parameters

NameTypeDefaultDescription
fill'row' | 'column''column'

Can be 'column' or 'row'. Defines how slides should fill rows, by column or by row

if used with loop mode make sure number of slides is even specified in loop mode requirements, or enable loopAddBlankSlides parameter

rowsnumber1

Number of slides rows, for multirow layout

Manipulation

操作模块添加了实用的 Swiper 方法来操作幻灯片。仅在 Swiper Core 版本中使用它才有意义,不建议与 Swiper React 或 Vue 一起使用。

¥Manipulation module adds useful Swiper methods to manipulate slides. It makes sense to use it only with Swiper Core version, not intended to be uses with Swiper React or Vue.

操作方法

¥Manipulation Methods

Methods
swiper.addSlide(index, slides)

Add new slides to the required index. slides could be HTMLElement or HTML string with new slide or array with such slides, for example:

addSlide(1, '<div class="swiper-slide">Slide 10"</div>')

addSlide(1, [
 '<div class="swiper-slide">Slide 10"</div>',
 '<div class="swiper-slide">Slide 11"</div>'
]);
swiper.appendSlide(slides)

Add new slides to the end. slides could be HTMLElement or HTML string with new slide or array with such slides, for example:

appendSlide('<div class="swiper-slide">Slide 10"</div>')

appendSlide([
 '<div class="swiper-slide">Slide 10"</div>',
 '<div class="swiper-slide">Slide 11"</div>'
]);
swiper.prependSlide(slides)

Add new slides to the beginning. slides could be HTMLElement or HTML string with new slide or array with such slides, for example:

prependSlide('<div class="swiper-slide">Slide 0"</div>')

prependSlide([
 '<div class="swiper-slide">Slide 1"</div>',
 '<div class="swiper-slide">Slide 2"</div>'
]);
swiper.removeAllSlides()

Remove all slides

swiper.removeSlide(slideIndex)

Remove selected slides. slideIndex could be a number with slide index to remove or array with indexes.

removeSlide(0); // remove first slide
removeSlide([0, 1]); // remove first and second slides
removeAllSlides();    // Remove all slides

Parallax

Swiper 支持 swiper/slides 嵌套元素的视差过渡效果。支持两种类型的视差元素:

¥Swiper supports parallax transition effects for swiper/slides nested elements. There are two types of parallax elements supported:

  • swiper 的直接子元素。此类元素的视差效果取决于滑块的总进度。用于视差背景

    ¥Direct child elements of swiper. Parallax effect for such elements will depend on total slider progress. Useful for parallax backgrounds

  • 滑动子元素。此类元素的视差效果取决于滑动进度。

    ¥Slides child elements. Parallax effect for such elements will depend on slide progress

要启用视差效果,你需要使用传递的 parallax:true 参数初始化 Swiper,并在所需元素中添加以下属性之一(或混合使用):

¥To enable parallax effects you need to init Swiper with passed parallax:true parameter and add one of the following (or mix) attributes to required elements:

  • data-swiper-parallax - 启用 transform-translate 视差过渡。此属性可接受:

    ¥data-swiper-parallax - enable transform-translate parallax transition. This attribute may accept:

    • number - 以 px 为单位的值(与上例中的标题和副标题相同),根据进度移动元素。在这种情况下,该元素将根据幻灯片位置(下一个或上一个)以 px 为单位移动 ± 此值。

      ¥number - value in px (as for title, subtitle in example above) to move element depending on progress. In this case such element will be moved on ± this value in px depending on slide position (next or previous)

    • percentage - (与 "parallax-bg" 相同)根据进度和大小移动元素。在这种情况下,此类元素将根据滑动位置(下一个或上一个)在其大小的±百分比(水平方向的宽度和垂直方向的高度)上移动。如果元素宽度为 400px,并且你指定了 data-swiper-parallax="50%",那么它将移动 ± 200px。

      ¥percentage - (as for "parallax-bg") to move element depending on progress and on its size. In this case such element will be moved on ± this percentage of its size (width in horizontal direction, and height in vertical direction) depending on slide position (next or previous). So if element has 400px width and you specified data-swiper-parallax="50%" then it will be moved on ± 200px

  • data-swiper-parallax-x - 相同,但 x 轴方向

    ¥data-swiper-parallax-x - same but for x-axis direction

  • data-swiper-parallax-y - y 轴方向相同

    ¥data-swiper-parallax-y - same but for y-axis direction

  • data-swiper-parallax-scale - 视差元素处于 "inactive"(非活动幻灯片)状态时的缩放比例

    ¥data-swiper-parallax-scale - scale ratio of the parallax element when it is in "inactive" (not on active slide) state

  • data-swiper-parallax-opacity - 视差元素处于 "inactive"(不在活动幻灯片上)状态时的不透明度

    ¥data-swiper-parallax-opacity - opacity of the parallax element when it is in "inactive" (not on active slide) state

  • data-swiper-parallax-duration - 视差元素的自定义过渡时长

    ¥data-swiper-parallax-duration - custom transition duration for parallax elements

<div class="swiper">
  <!-- Parallax background element -->
  <div
    class="parallax-bg"
    style="background-image:url(path/to/image.jpg)"
    data-swiper-parallax="-23%"
  ></div>
  <div class="swiper-wrapper">
    <div class="swiper-slide">
      <!-- Each slide has parallax title -->
      <div class="title" data-swiper-parallax="-100">Slide 1</div>
      <!-- Parallax subtitle -->
      <div class="subtitle" data-swiper-parallax="-200">Subtitle</div>
      <!-- And parallax text with custom transition duration -->
      <div
        class="text"
        data-swiper-parallax="-300"
        data-swiper-parallax-duration="600"
      >
        <p>Lorem ipsum dolor sit amet, ...</p>
      </div>
      <!-- Opacity parallax -->
      <div data-swiper-parallax-opacity="0.5">I will change opacity</div>
      <!-- Scale parallax -->
      <div data-swiper-parallax-scale="0.15">I will change scale</div>
    </div>
    ...
  </div>
</div>

视差参数

¥Parallax Parameters

NameTypeDefaultDescription
enabledbooleanfalse

Enable, if you want to use "parallaxed" elements inside of slider

Lazy Loading

自版本 9 起,Swiper 没有特定的延迟加载 API,因为它依赖于浏览器原生的延迟加载功能。要使用延迟加载,我们只需在图片上设置 loading="lazy" 并添加预加载器元素:

¥Since version 9 Swiper doesn't have a specific lazy loading API, as it relies on native browser lazy loading feature. To use lazy loading, we just need to set loading="lazy" on images and add preloader element:

<div class="swiper">
  <div class="swiper-wrapper">
    <!-- Lazy image -->
    <div class="swiper-slide">
      <img src="path/to/picture-1.jpg" loading="lazy" />
      <div class="swiper-lazy-preloader"></div>
    </div>

    <!-- Lazy image with srcset -->
    <div class="swiper-slide">
      <img
        src="path/to/logo-small.png"
        srcset="path/to/logo-large.png 2x"
        loading="lazy"
      />
      <div class="swiper-lazy-preloader"></div>
    </div>
  </div>
</div>

如你所见:

¥As you see:

  • 延迟加载图片必须具有 loading="lazy" 属性

    ¥Lazy image must have loading="lazy" attribute

  • 为幻灯片添加动画预加载器,该动画将在图片加载后自动移除:

    ¥Add animated preloader spinner to slide which will be removed automatically after image loaded:

<div class="swiper-lazy-preloader"></div>

或者,在深色布局中使用白色元素:

¥Or white one for dark layout:

<div class="swiper-lazy-preloader swiper-lazy-preloader-white"></div>

Fade Effect

请确保将 effect 参数设置为 'fade' 才能使其正常工作。

¥Be sure to have the effect param set to 'fade' in order for this to work.

Note that crossFade should be set to true in order to avoid seeing content behind or underneath.

淡入淡出效果参数

¥Fade Effect Parameters

NameTypeDefaultDescription
crossFadebooleanfalse

Enables slides cross fade

Coverflow Effect

请确保将 effect 参数设置为 'coverflow' 才能使其正常工作。

¥Be sure to have the effect param set to 'coverflow' in order for this to work.

Coverflow 效果参数

¥Coverflow Effect Parameters

NameTypeDefaultDescription
depthnumber100

Depth offset in px (slides translate in Z axis)

modifiernumber1

Effect multiplier

rotatenumber50

Slide rotate in degrees

scalenumber1

Slide scale effect

slideShadowsbooleantrue

Enables slides shadows

stretchnumber0

Stretch space between slides (in px)

Flip Effect

请确保将 effect 参数设置为 'flip' 才能使其正常工作。

¥Be sure to have the effect param set to 'flip' in order for this to work.

翻转效果参数

¥Flip Effect Parameters

NameTypeDefaultDescription
limitRotationbooleantrue

Limit edge slides rotation

slideShadowsbooleantrue

Enables slides shadows

Cube Effect

请确保将 effect 参数设置为 'cube' 才能使其正常工作。

¥Be sure to have the effect param set to 'cube' in order for this to work.

立方体效果参数

¥Cube Effect Parameters

NameTypeDefaultDescription
shadowbooleantrue

Enables main slider shadow

shadowOffsetnumber20

Main shadow offset in px

shadowScalenumber0.94

Main shadow scale ratio

slideShadowsbooleantrue

Enables slides shadows

Cards Effect

请确保将 effect 参数设置为 'cards' 才能使其正常工作。

¥Be sure to have the effect param set to 'cards' in order for this to work.

卡片效果参数

¥Cards Effect Parameters

NameTypeDefaultDescription
perSlideOffsetnumber8

Offset distance per slide (in px)

perSlideRotatenumber2

Rotate angle per slide (in degrees)

rotatebooleantrue

Enables cards rotation

slideShadowsbooleantrue

Enables slides shadows

Creative Effect

请确保将 effect 参数设置为 'creative' 才能使其正常工作。

¥Be sure to have the effect param set to 'creative' in order for this to work.

创意效果参数

¥Creative Effect Parameters

NameTypeDefaultDescription
limitProgressnumber1

Limit progress/offset to amount of side slides. If 1, then slides all slides after prev/next will have same state. If 2, then all slides after 2nd before/after active will have same state, etc.

nextCreativeEffectTransform

Next slide transformations.

{
  // Array with translate X, Y and Z values
  translate: (string | number)[];
  // Array with rotate X, Y and Z values (in deg)
  rotate?: number[];
  // Slide opacity
  opacity?: number;
  // Slide scale
  scale?: number;
  // Enables slide shadow
  shadow?: boolean;
  // Transform origin, e.g. `left bottom`
  origin?: string;
}
perspectivebooleantrue

Enable this parameter if your custom transforms require 3D transformations (translateZ, rotateX, rotateY )

prevCreativeEffectTransform

Previous slide transformations. Accepts object of the following type:

{
  // Array with translate X, Y and Z values
  translate: (string | number)[];
  // Array with rotate X, Y and Z values (in deg)
  rotate?: number[];
  // Slide opacity
  opacity?: number;
  // Slide scale
  scale?: number;
  // Enables slide shadow
  shadow?: boolean;
  // Transform origin, e.g. `left bottom`
  origin?: string;
}
progressMultipliernumber1

Allows to multiply slides transformations and opacity.

shadowPerProgressbooleanfalse

Splits shadow "opacity" per slide based on limitProgress (only if transformation shadows enabled). E.g. setting limitProgress: 2 and enabling shadowPerProgress, will set shadow opacity to 0.5 and 1 on two slides next to active. With this parameter disabled, all slides beside active will have shadow with 1 opacity

Thumbs

除了 控制器 组件外,Swiper 还附带 Thumbs 组件,该组件旨在以比用于同步两个滑动条的 Controller 更正确的方式与多个滑动条协同工作。

¥In addition to Controller component Swiper comes with Thumbs component that is designed to work with additional thumbs swiper in a more correct way than Controller which is used for syncing two swipers.

缩略图参数

¥Thumbs Parameters

NameTypeDefaultDescription
autoScrollOffsetnumber0

Allows to set on which thumbs active slide from edge it should automatically move scroll thumbs. For example, if set to 1 and last visible thumb will be activated (1 from edge) it will auto scroll thumbs

multipleActiveThumbsbooleantrue

When enabled multiple thumbnail slides may get activated

slideThumbActiveClassstring'swiper-slide-thumb-active'

Additional class that will be added to activated thumbs swiper slide

swiperanynull

Swiper instance of swiper used as thumbs or object with Swiper parameters to initialize thumbs swiper

thumbsContainerClassstring'swiper-thumbs'

Additional class that will be added to thumbs swiper

缩略图方法

¥Thumbs Methods

Properties
swiper.swiperany

Swiper instance of thumbs swiper

Methods
swiper.init()

Initialize thumbs

swiper.update(initial)

Update thumbs

Zoom

Swiper 支持缩放图片功能(类似于 iOS 上浏览单张照片时的功能),你可以通过捏合手势放大图片,或双击图片进行放大/缩小。在这种情况下,需要额外的布局:

¥Swiper supports zoom images functionality (similar to what you see on iOS when browsing single photo) where you can zoom-in image by pinch gesture and or by zoom-in/out by double tap on it. In this case, additional layout is required:

<div class="swiper">
  <div class="swiper-wrapper">
    <div class="swiper-slide">
      <div class="swiper-zoom-container">
        <img src="path/to/image1.jpg" />
      </div>
    </div>
    <div class="swiper-slide">
      <div class="swiper-zoom-container">
        <img src="path/to/image2.jpg" />
      </div>
    </div>
    <div class="swiper-slide">Plain slide with text</div>
    <div class="swiper-slide">
      <!-- Override maxRatio parameter -->
      <div class="swiper-zoom-container" data-swiper-zoom="5">
        <img src="path/to/image1.jpg" />
      </div>
    </div>
  </div>
</div>
  • 所有 "zoomable" 图片都应使用带有 swiper-zoom-container 类的 div 包裹。

    ¥All "zoomable" images should be wrapped with the div with swiper-zoom-container class.

  • 默认情况下,它会缩放 imgpicturecanvas 元素之一。如果你想对其他自定义元素进行缩放,只需将 swiper-zoom-target 类添加到此元素即可。例如:

    ¥By default it expects to zoom one of the img, picture or canvas element. If you want to make zoom on some other custom element, then just add swiper-zoom-target class to this element. For example:

    <div class="swiper">
      <div class="swiper-wrapper">
        <div class="swiper-slide">
          <div class="swiper-zoom-container">
            <!-- custom zoomable element -->
            <div
              class="swiper-zoom-target"
              style="background-image: url(...)"
            ></div>
          </div>
        </div>
      </div>
    </div>
    
  • 你可以使用缩放容器上的 data-swiper-zoom 属性覆盖特定幻灯片的 maxRatio 参数。

    ¥You can override maxRatio parameter for specific slides by using data-swiper-zoom attribute on zoom container.

缩放参数

¥Zoom Parameters

NameTypeDefaultDescription
containerClassstring'swiper-zoom-container'

CSS class name of zoom container

limitToOriginalSizebooleanfalse

When set to true, the image will not be scaled past 100% of its original size

maxRationumber3

Maximum image zoom multiplier

minRationumber1

Minimal image zoom multiplier

panOnMouseMovebooleanfalse

When set to true, a zoomed in image will automatically pan while moving the mouse over the image

togglebooleantrue

Enable/disable zoom-in by slide's double tap

zoomedSlideClassstring'swiper-slide-zoomed'

CSS class name of zoomed in container

缩放方法

¥Zoom Methods

Properties
swiper.enabledboolean

Whether the zoom module is enabled

swiper.scalenumber

Current image scale ratio

Methods
swiper.disable()

Disable zoom module

swiper.enable()

Enable zoom module

swiper.in(ratio)

Zoom in image of the currently active slide. Optionally accepts custom zoom ratio

swiper.out()

Zoom out image of the currently active slide

swiper.toggle(event)

Toggle image zoom of the currently active slide

缩放事件

¥Zoom Events

NameArgumentsDescription
zoomChange(swiper, scale, imageEl, slideEl)

Event will be fired on zoom change

Keyboard Control

键盘控制参数

¥Keyboard Control Parameters

NameTypeDefaultDescription
enabledbooleanfalse

Set to true to enable keyboard control

onlyInViewportbooleantrue

When enabled it will control sliders that are currently in viewport

pageUpDownbooleantrue

When enabled it will enable keyboard navigation by Page Up and Page Down keys

键盘控制方法

¥Keyboard Control Methods

Properties
swiper.enabledboolean

Whether the keyboard control is enabled

Methods
swiper.disable()

Disable keyboard control

swiper.enable()

Enable keyboard control

键盘事件

¥Keyboard Events

NameArgumentsDescription
keyPress(swiper, keyCode)

Event will be fired on key press

Mousewheel Control

鼠标滚轮控制参数

¥Mousewheel Control Parameters

NameTypeDefaultDescription
enabledbooleanfalse

Set to true to enable mousewheel control

eventsTargetany'container'

String with CSS selector or HTML element of the container accepting mousewheel events. By default it is swiper

forceToAxisbooleanfalse

Set to true to force mousewheel swipes to axis. So in horizontal mode mousewheel will work only with horizontal mousewheel scrolling, and only with vertical scrolling in vertical mode.

invertbooleanfalse

Set to true to invert sliding direction

noMousewheelClassstring'swiper-no-mousewheel'

Scrolling on elements with this class will be ignored

releaseOnEdgesbooleanfalse

Set to true and swiper will release mousewheel event and allow page scrolling when swiper is on edge positions (in the beginning or in the end)

sensitivitynumber1

Multiplier of mousewheel data, allows to tweak mouse wheel sensitivity

thresholdDeltanull | numbernull

Minimum mousewheel scroll delta to trigger swiper slide change

thresholdTimenull | numbernull

Minimum mousewheel scroll time delta (in ms) to trigger swiper slide change

鼠标滚轮控制方法

¥Mousewheel Control Methods

Properties
swiper.enabledboolean

Whether the mousewheel control is enabled

Methods
swiper.disable()

Disable mousewheel control

swiper.enable()

Enable mousewheel control

鼠标滚轮事件

¥Mousewheel Events

NameArgumentsDescription
scroll(swiper, event)

Event will be fired on mousewheel scroll

Virtual Slides

虚拟幻灯片模块允许​​在 DOM 中保留所需数量的幻灯片。如果你有大量幻灯片,尤其是包含重量级 DOM 树或图片的幻灯片,它在性能和内存方面非常有用。

¥Virtual Slides module allows to keep just required amount of slides in DOM. It is very useful in terms in performance and memory issues if you have a lot of slides, especially slides with heavyweight DOM tree or images.

Note that according to Virtual Slides realization it doesn't work with Grid module and slidesPerView: 'auto'

虚拟幻灯片参数

¥Virtual Slides Parameters

NameTypeDefaultDescription
addSlidesAfternumber0

Increases amount of pre-rendered slides after active slide

addSlidesBeforenumber0

Increases amount of pre-rendered slides before active slide

cachebooleantrue

Enables DOM cache of rendering slides html elements. Once they are rendered they will be saved to cache and reused from it.

enabledbooleanfalse

Whether the virtual slides are enabled

renderExternalfunction(data)

Function for external rendering (e.g. using some other library to handle DOM manipulations and state like React.js or Vue.js). As an argument it accepts data object with the following properties:

  • offset - slides left/top offset in px
  • from - index of first slide required to be rendered
  • to - index of last slide required to be rendered
  • slides - array with slide items to be rendered
renderExternalUpdatebooleantrue

When enabled (by default) it will update Swiper layout right after renderExternal called. Useful to disable and update swiper manually when used with render libraries that renders asynchronously

renderSlidefunction(slide, index)

Function to render slide. As an argument it accepts current slide item for slides array and index number of the current slide. Function must return an outer HTML of the swiper slide or slide HTML element.

slidesT[][]

Array with slides

虚拟幻灯片方法

¥Virtual Slides Methods

Properties
swiper.cacheobject

Object with cached slides HTML elements

swiper.fromnumber

Index of first rendered slide

swiper.slidesT[]

Array with slide items passed by virtual.slides parameter

swiper.tonumber

Index of last rendered slide

Methods
swiper.appendSlide(slide)

Append slide. slides can be a single slide item or array with such slides.

Only for Core version (in React & Vue it should be done by modifying slides array/data/source)

swiper.prependSlide(slide)

Prepend slide. slides can be a single slide item or array with such slides.

Only for Core version (in React & Vue it should be done by modifying slides array/data/source)

swiper.removeAllSlides()

Remove all slides

Only for Core version (in React & Vue it should be done by modifying slides array/data/source)

swiper.removeSlide(slideIndexes)

Remove specific slide or slides. slideIndexes can be a number with slide index to remove or array with indexes.

Only for Core version (in React & Vue it should be done by modifying slides array/data/source)

swiper.update(force)

Update virtual slides state

虚拟幻灯片 Dom

¥Virtual Slides Dom

自版本 9 起,Swiper 虚拟幻灯片可以与最初在 DOM 中渲染的幻灯片一起使用。初始化时,它会从 DOM 中移除这些元素,进行缓存,然后重新使用需要的元素:

¥Since version 9, Swiper virtual slides can work with slides originally rendered in DOM. On initialize it will remove them from DOM, cache and then re-use the ones which are required:

<div class="swiper">
  <div class="swiper-wrapper">
    <div class="swiper-slide">Slide 1</div>
    <div class="swiper-slide">Slide 2</div>
    ...
    <div class="swiper-slide">Slide 100</div>
  </div>
</div>
<script>
  const swiper = new Swiper('.swiper', {
    virtual: {
      enabled: true,
    },
  });
</script>

Hash Navigation

哈希导航旨在提供指向特定幻灯片的链接,以便在打开特定幻灯片时加载页面。

¥Hash navigation is intended to have a link to specific slide that allows to load page with specific slide opened.

要使其正常工作,你需要通过传递 hashNavigation:true 参数并在 data-hash 属性中添加幻灯片哈希值来启用它:

¥To make it work, you need to enable it by passing hashNavigation:true parameter and adding slides hashes in data-hash attribute:

<div class="swiper">
  <div class="swiper-wrapper">
    <div class="swiper-slide" data-hash="slide1">Slide 1</div>
    <div class="swiper-slide" data-hash="slide2">Slide 2</div>
    <div class="swiper-slide" data-hash="slide3">Slide 3</div>
    <div class="swiper-slide" data-hash="slide4">Slide 4</div>
    <div class="swiper-slide" data-hash="slide5">Slide 5</div>
    ...
  </div>
</div>
const swiper = new Swiper('.swiper', {
  //enable hash navigation
  hashNavigation: true,
});

哈希导航参数

¥Hash Navigation Parameters

NameTypeDefaultDescription
getSlideIndexfunction(swiper, hash)

Designed to be used with Virtual slides when it is impossible to find slide in DOM by hash (e.g. not yet rendered)

replaceStatebooleanfalse

Works in addition to hashnav to replace current url state with the new one instead of adding it to history

watchStatebooleanfalse

Set to true to enable also navigation through slides (when hashnav is enabled) by browser history or by setting directly hash on document location

哈希导航事件

¥Hash Navigation Events

NameArgumentsDescription
hashChange(swiper)

Event will be fired on window hash change

hashSet(swiper)

Event will be fired when swiper updates the hash

History Navigation

历史导航参数

¥History Navigation Parameters

NameTypeDefaultDescription
enabledbooleanfalse

Enables History Plugin.

keepQuerybooleanfalse

Keep query parameters when changing browser url.

keystring'slides'

Url key for slides

replaceStatebooleanfalse

Works in addition to hashnav or history to replace current url state with the new one instead of adding it to history

rootstring''

Swiper page root, useful to specify when you use Swiper history mode not on root website page. For example can be https://my-website.com/ or https://my-website.com/subpage/ or /subpage/

Controller

控制器参数

¥Controller Parameters

NameTypeDefaultDescription
by'slide' | 'container''slide'

Defines a way how to control another slider: slide by slide (with respect to other slider's grid) or depending on all slides/container (depending on total slider percentage).

controlany

Pass here another Swiper instance or array with Swiper instances that should be controlled by this Swiper. Also accepts string with CSS selector of Swiper element, or HTMLElement of Swiper element

inversebooleanfalse

Set to true and controlling will be in inverse direction

控制器方法

¥Controller Methods

Properties
swiper.controlany

Pass here another Swiper instance or array with Swiper instances that should be controlled by this Swiper

Accessibility (a11y)

辅助功能参数

¥Accessibility Parameters

NameTypeDefaultDescription
containerMessagenull | stringnull

Message for screen readers for outer swiper container

containerRolenull | stringnull

Value of the "role" attribute to be set on the swiper container

containerRoleDescriptionMessagenull | stringnull

Message for screen readers describing the role of outer swiper container

enabledbooleantrue

Enables A11y

firstSlideMessagestring'This is the first slide'

Message for screen readers for previous button when swiper is on first slide

idnull | string | numbernull

Value of id attribute to be set on swiper-wrapper. If null will be generated automatically

itemRoleDescriptionMessagenull | stringnull

Message for screen readers describing the role of slide element

lastSlideMessagestring'This is the last slide'

Message for screen readers for next button when swiper is on last slide

nextSlideMessagestring'Next slide'

Message for screen readers for next button

notificationClassstring'swiper-notification'

CSS class name of A11y notification

paginationBulletMessagestring'Go to slide {{index}}'

Message for screen readers for single pagination bullet

prevSlideMessagestring'Previous slide'

Message for screen readers for previous button

scrollOnFocusbooleantrue

Enables scrolling to the slide that has been focused

slideLabelMessagestring'{{index}} / {{slidesLength}}'

Message for screen readers describing the label of slide element

slideRolestring'group'

Value of swiper slide role attribute

自定义构建

¥Custom Build

你有两种方法可以创建自定义版本的 Swiper。

¥You have two options of making custom version of Swiper.

使用 JS 模块

¥Using JS Modules

如果你在项目中使用支持 JS 模块的 bundler,则可以只导入所需的模块:

¥If you use bundler with JS modules support in your project you can import only the modules you need:

// Import Swiper and modules
import Swiper from 'swiper';
import { Navigation, Pagination, Scrollbar } from 'swiper/modules';

// Now you can use Swiper
const swiper = new Swiper('.swiper', {
  // Install modules
  modules: [Navigation, Pagination, Scrollbar],
  speed: 500,
  navigation: {
    nextEl: '.swiper-button-next',
    prevEl: '.swiper-button-prev',
  },
  // ...
});

可导出模块如下:

¥The following modules are exported:

  • Virtual - 虚拟幻灯片模块

    ¥Virtual - Virtual Slides module

  • Keyboard - 键盘控制模块

    ¥Keyboard - Keyboard Control module

  • Mousewheel - 鼠标滚轮控制模块

    ¥Mousewheel - Mousewheel Control module

  • Navigation - 导航模块

    ¥Navigation - Navigation module

  • Pagination - 分页模块

    ¥Pagination - Pagination module

  • Scrollbar - 滚动条模块

    ¥Scrollbar - Scrollbar module

  • Parallax - 视差模块

    ¥Parallax - Parallax module

  • FreeMode - 自由模式模块

    ¥FreeMode - Free Mode module

  • Grid - 网格模块

    ¥Grid - Grid module

  • Manipulation - 幻灯片操作模块(仅适用于核心版本)

    ¥Manipulation - Slides manipulation module (only for Core version)

  • Zoom - 缩放模块

    ¥Zoom - Zoom module

  • Controller - 控制器模块

    ¥Controller - Controller module

  • A11y - 辅助功能模块

    ¥A11y - Accessibility module

  • History - 历史导航模块

    ¥History - History Navigation module

  • HashNavigation - 哈希导航模块

    ¥HashNavigation - Hash Navigation module

  • Autoplay - 自动播放模块

    ¥Autoplay - Autoplay module

  • EffectFade - 淡入淡出效果模块

    ¥EffectFade - Fade Effect module

  • EffectCube - 立方体效果模块

    ¥EffectCube - Cube Effect module

  • EffectFlip - 翻转效果模块

    ¥EffectFlip - Flip Effect module

  • EffectCoverflow - Coverflow 效果模块

    ¥EffectCoverflow - Coverflow Effect module

  • EffectCards - 卡片效果模块

    ¥EffectCards - Cards Effect module

  • EffectCreative - 创意效果模块

    ¥EffectCreative - Creative Effect module

  • Thumbs - 缩略图模块

    ¥Thumbs - Thumbs module

使用 Build 脚本

¥Using Build Script

Swiper 附带 gulp 构建器,允许你构建自定义库版本,其中你可以只包含所需的模块。我们需要以下内容:

¥Swiper comes with gulp builder that allows to build custom library version where you may include only required modules. We need the following:

  1. 下载并解压 Swiper GitHub 仓库 到本地文件夹

    ¥Download and unzip Swiper GitHub repository to local folder

  2. 安装 Node.js(如果尚未安装)

    ¥Install Node.js (if not installed)

  3. 现在,我们需要安装所需的依赖。前往下载并解压的 Swiper 代码库所在的文件夹,并在终端中执行:

    ¥Now, we need to install required dependencies. Go to the folder with downloaded and unzipped Swiper repository and execute in terminal:

    $ npm install
    
  4. 打开 scripts/build-config.js 文件:

    ¥Open scripts/build-config.js file:

    module.exports = {
      // remove modules you don't need
      modules: [
        'virtual',
        'keyboard',
        'mousewheel',
        'navigation',
        'pagination',
        'scrollbar',
        'parallax',
        'zoom',
        'controller',
        'a11y',
        'history',
        'hash-navigation',
        'autoplay',
        'thumbs',
        'free-mode',
        'grid',
        'manipulation',
        'effect-fade',
        'effect-cube',
        'effect-flip',
        'effect-coverflow',
        'effect-creative',
        'effect-cards',
      ],
    };
    
  5. 现在,我们可以构建自定义版本的 Swiper 了:

    ¥Now, we are ready to build custom version of Swiper:

    $ npm run build:prod
    
  6. 就是这样。生成的 CSS 和 JS 文件及其压缩版本将在 dist/ 文件夹。

    ¥That is all. Generated CSS and JS files and their minified versions will be available in dist/ folder.

TypeScript 定义

¥TypeScript Definitions

Swiper 是完全类型化的,它导出 SwiperSwiperOptions 类型:

¥Swiper is fully typed, it exports Swiper and SwiperOptions types:

// main.ts
import Swiper from 'swiper';
import { SwiperOptions } from 'swiper/types';

const swiperParams: SwiperOptions = {
  slidesPerView: 3,
  spaceBetween: 50,
};

const swiper = new Swiper('.swiper', swiperParams);

你还可以检查自动生成的 TypeScript definitions explorer 的所有类型、选项、属性和方法。

¥You can also check auto generated TypeScript definitions explorer for all the types, options, properties and methods.