¥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 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 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
¥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:
Name | Type | Default | Description |
---|---|---|---|
a11y | any | Object with a11y parameters or boolean
| |
allowSlideNext | boolean | true | Set to |
allowSlidePrev | boolean | true | Set to |
allowTouchMove | boolean | true | If |
autoHeight | boolean | false | Set to |
autoplay | any | Object with autoplay parameters or boolean
| |
breakpoints | object | 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
| |
breakpointsBase | any | 'window' | Base for breakpoints (beta). Can be |
cardsEffect | any | Object with Cards-effect parameters
| |
centerInsufficientSlides | boolean | false | When enabled it center slides if the amount of slides less than |
centeredSlides | boolean | false | If |
centeredSlidesBounds | boolean | false | If |
containerModifierClass | string | 'swiper-' | The beginning of the modifier CSS class that can be added to swiper container depending on different parameters |
controller | any | Object with controller parameters or boolean
| |
coverflowEffect | any | Object with Coverflow-effect parameters.
| |
createElements | boolean | false | 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 |
creativeEffect | any | Object with Creative-effect parameters
| |
cssMode | boolean | false | 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:
In case if you use it with other effects, especially 3D effects, it is required to wrap slide's content with
|
cubeEffect | any | Object with Cube-effect parameters
| |
direction | 'horizontal' | 'vertical' | 'horizontal' | Can be |
edgeSwipeDetection | string | boolean | false | Enable to release Swiper events for swipe-back work in app. If set to |
edgeSwipeThreshold | number | 20 | Area (in px) from left edge of the screen to release touch events for swipe-back in app |
effect | string | 'slide' | Transition effect. Can be |
enabled | boolean | true | Whether Swiper initially enabled. When Swiper is disabled, it will hide all navigation elements and won't respond to any events and interactions |
eventsPrefix | string | `swiper` | Event name prefix for all DOM events emitted by Swiper Element (web component) |
fadeEffect | any | Object with Fade-effect parameters
| |
flipEffect | any | Object with Flip-effect parameters
| |
focusableElements | string | 'input, select, option, textarea, button, video, label' | CSS selector for focusable elements. Swiping will be disabled on such elements if they are "focused" |
followFinger | boolean | true | If disabled, then slider will be animated only when you release it, it will not move while you hold your finger on it |
freeMode | any | Enables free mode functionality. Object with free mode parameters or boolean
| |
grabCursor | boolean | false | This option may a little improve desktop usability. If |
grid | any | Object with grid parameters to enable "multirow" slider.
| |
hashNavigation | any | Enables hash url navigation to for slides. Object with hash navigation parameters or boolean
| |
height | null | number | null | 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
|
history | any | Enables history push state where every slide will have its own url. In this parameter you have to specify main slides url like Object with history navigation parameters or boolean
| |
init | boolean | true | Whether Swiper should be initialised automatically when you create an instance. If disabled, then you need to init it manually by calling |
initialSlide | number | 0 | Index number of initial slide. |
injectStyles | string[] | Inject text styles to the shadow DOM. Only for usage with Swiper Element | |
injectStylesUrls | string[] | Inject styles | |
keyboard | any | Enables navigation through slides using keyboard. Object with keyboard parameters or boolean
| |
lazyPreloadPrevNext | number | 0 | Number of next and previous slides to preload. Only applicable if using lazy loading. |
lazyPreloaderClass | string | 'swiper-lazy-preloader' | CSS class name of lazy preloader |
longSwipes | boolean | true | Set to |
longSwipesMs | number | 300 | Minimal duration (in ms) to trigger swipe to next/previous slide during long swipes |
longSwipesRatio | number | 0.5 | Ratio to trigger swipe to next/previous slide during long swipes |
loop | boolean | false | Set to Because of nature of how the loop mode works (it will rearrange slides), total number of slides must be:
|
loopAddBlankSlides | boolean | true | Automatically adds blank slides if you use Grid or |
loopAdditionalSlides | number | 0 | Allows to increase amount of looped slides |
loopPreventsSliding | boolean | true | If enabled then slideNext/Prev will do nothing while slider is animating in loop mode |
maxBackfaceHiddenSlides | number | 10 | If total number of slides less than specified here value, then Swiper will enable
|
modules | any[] | Array with Swiper modules
| |
mousewheel | any | Enables navigation through slides using mouse wheel. Object with mousewheel parameters or boolean
| |
navigation | any | Object with navigation parameters or boolean
| |
nested | boolean | false | Set to |
noSwiping | boolean | true | Enable/disable swiping on elements matched to class specified in |
noSwipingClass | string | 'swiper-no-swiping' | Specify |
noSwipingSelector | string | Can be used instead of | |
normalizeSlideIndex | boolean | true | Normalize slide index. |
observeParents | boolean | false | Set to |
observeSlideChildren | boolean | false | Set to |
observer | boolean | false | Set to |
on | object | Register event handlers | |
onAny | function(handler) | Add event listener that will be fired on all events
| |
oneWayMovement | boolean | false | When enabled, will swipe slides only forward (one-way) regardless of swipe direction |
pagination | any | Object with pagination parameters or boolean
| |
parallax | any | Object with parallax parameters or boolean
| |
passiveListeners | boolean | true | Passive event listeners will be used by default where possible to improve scrolling performance on mobile devices. But if you need to use |
preventClicks | boolean | true | Set to |
preventClicksPropagation | boolean | true | Set to |
preventInteractionOnTransition | boolean | false | When enabled it won't allow to change slides by swiping or navigation/pagination buttons during transition |
resistance | boolean | true | Set to |
resistanceRatio | number | 0.85 | This option allows you to control resistance ratio |
resizeObserver | boolean | true | When enabled it will use ResizeObserver (if supported by browser) on swiper container to detect container resize (instead of watching for window resize) |
rewind | boolean | false | Set to
|
roundLengths | boolean | false | Set to |
runCallbacksOnInit | boolean | true | 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 |
scrollbar | any | Object with scrollbar parameters or boolean
| |
setWrapperSize | boolean | false | 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 |
shortSwipes | boolean | true | Set to |
simulateTouch | boolean | true | If |
slideActiveClass | string | 'swiper-slide-active' | CSS class name of currently active slide
|
slideBlankClass | string | 'swiper-slide-blank' | CSS class name of the blank slide added by the loop mode (when
|
slideClass | string | 'swiper-slide' | CSS class name of slide
|
slideFullyVisibleClass | string | 'swiper-slide-fully-visible' | CSS class name of fully (when whole slide is in the viewport) visible slide
|
slideNextClass | string | 'swiper-slide-next' | CSS class name of slide which is right after currently active slide
|
slidePrevClass | string | 'swiper-slide-prev' | CSS class name of slide which is right before currently active slide
|
slideToClickedSlide | boolean | false | Set to |
slideVisibleClass | string | 'swiper-slide-visible' | CSS class name of currently/partially visible slide
|
slidesOffsetAfter | number | 0 | Add (in px) additional slide offset in the end of the container (after all slides) |
slidesOffsetBefore | number | 0 | Add (in px) additional slide offset in the beginning of the container (before all slides) |
slidesPerGroup | number | 1 | Set numbers of slides to define and enable group sliding. Useful to use with slidesPerView > 1 |
slidesPerGroupAuto | boolean | false | This param intended to be used only with |
slidesPerGroupSkip | number | 0 | The parameter works in the following way: If If |
slidesPerView | number | 'auto' | 1 | Number of slides per view (slides visible at the same time on slider's container).
|
spaceBetween | string | number | 0 | Distance between slides in px.
|
speed | number | 300 | Duration of transition between slides (in ms) |
swipeHandler | any | null | String with CSS selector or HTML element of the container with pagination that will work as only available handler for swiping |
swiperElementNodeName | string | 'SWIPER-CONTAINER' | The name of the swiper element node name; used for detecting web component rendering |
threshold | number | 5 | Threshold value in px. If "touch distance" will be lower than this value then swiper will not move |
thumbs | any | Object with thumbs component parameters
| |
touchAngle | number | 45 | Allowable angle (in degrees) to trigger touch move |
touchEventsTarget | 'container' | 'wrapper' | 'wrapper' | Target element to listen touch events on. Can be |
touchMoveStopPropagation | boolean | false | If enabled, then propagation of "touchmove" will be stopped |
touchRatio | number | 1 | Touch ratio |
touchReleaseOnEdges | boolean | false | 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 |
touchStartForcePreventDefault | boolean | false | Force to always prevent default for |
touchStartPreventDefault | boolean | true | If disabled, |
uniqueNavElements | boolean | true | If enabled (by default) and navigation elements' parameters passed as a string (like |
updateOnWindowResize | boolean | true | Swiper will recalculate slides position on window resize (orientationchange) |
url | null | string | null | Required for active slide detection when rendered on server-side and enabled history |
userAgent | null | string | null | userAgent string. Required for browser/device detection when rendered on server-side |
virtual | any | Enables virtual slides functionality. Object with virtual slides parameters or boolean
| |
virtualTranslate | boolean | false | 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 |
watchOverflow | boolean | true | When enabled Swiper will be disabled and hide navigation buttons on case there are not enough slides for sliding. |
watchSlidesProgress | boolean | false | Enable this feature to calculate each slides progress and visibility (slides in viewport will have additional visible class) |
width | null | number | null | 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
|
wrapperClass | string | 'swiper-wrapper' | CSS class name of slides' wrapper
|
zoom | any | Enables zooming functionality. Object with zoom parameters or boolean
|
¥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.a11y | any | |
swiper.activeIndex | number | Index number of currently active slide
|
swiper.allowSlideNext | boolean | Disable / enable ability to slide to the next slides by assigning |
swiper.allowSlidePrev | boolean | Disable / enable ability to slide to the previous slides by assigning |
swiper.allowTouchMove | boolean | Disable / enable ability move slider by grabbing it with mouse or by touching it with finger (on touch screens) by assigning |
swiper.animating | boolean |
|
swiper.autoplay | any | |
swiper.cardsEffect | any | |
swiper.clickedIndex | number | Index number of last clicked slide |
swiper.clickedSlide | HTMLElement | Link to last clicked slide (HTMLElement) |
swiper.controller | any | |
swiper.coverflowEffect | any | |
swiper.creativeEffect | any | |
swiper.cubeEffect | any | |
swiper.defaults | any | Swiper default options |
swiper.el | HTMLElement | Slider container HTML element |
swiper.extendedDefaults | any | Object with global Swiper extended options |
swiper.fadeEffect | any | |
swiper.flipEffect | any | |
swiper.freeMode | any | |
swiper.hashNavigation | any | |
swiper.height | number | Height of container |
swiper.history | any | |
swiper.isBeginning | boolean |
|
swiper.isEnd | boolean |
|
swiper.isLocked | boolean |
|
swiper.keyboard | any | |
swiper.mousewheel | any | |
swiper.navigation | any | |
swiper.originalParams | any | Object with original initialization parameters |
swiper.pagination | any | |
swiper.parallax | any | |
swiper.params | any | Object with passed initialization parameters |
swiper.previousIndex | number | Index number of previously active slide |
swiper.progress | number | Current progress of wrapper translate (from 0 to 1) |
swiper.realIndex | number | Index number of currently active slide considering rearranged slides in loop mode |
swiper.scrollbar | any | |
swiper.slides | HTMLElement[] | Array of slides HTML elements. To get specific slide HTMLElement use |
swiper.slidesEl | HTMLElement | Wrapper HTML element |
swiper.slidesGrid | number[] | Slides grid |
swiper.slidesSizesGrid | number[] | Array of widths for slides |
swiper.snapGrid | number[] | Slides snap grid |
swiper.snapIndex | number | Index number of current snap in |
swiper.swipeDirection | 'prev' | 'next' | Direction of sliding |
swiper.thumbs | any | |
swiper.touches | object | Object with the following touch event properties:
|
swiper.translate | number | Current value of wrapper translate |
swiper.virtual | any | |
swiper.width | number | Width of container |
swiper.wrapperEl | HTMLElement | Wrapper HTML element |
swiper.zoom | any | |
Methods | ||
swiper.attachEvents() | Attach all events listeners again | |
swiper.changeDirection(direction, needUpdate) | Changes slider direction from horizontal to vertical and back.
| |
swiper.changeLanguageDirection(direction) | Changes slider language
| |
swiper.destroy(deleteInstance, cleanStyles) | Destroy slider instance and detach all events listeners
| |
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
| |
swiper.setTranslate(translate) | Set custom css3 transform's translate value for swiper wrapper | |
swiper.slideNext(speed, runCallbacks) | Run transition to next slide.
| |
swiper.slidePrev(speed, runCallbacks) | Run transition to previous slide.
| |
swiper.slideReset(speed, runCallbacks) | Reset swiper position to currently active slide for the duration equal to 'speed' parameter.
| |
swiper.slideTo(index, speed, runCallbacks) | Run transition to the slide with index number equal to 'index' parameter for the duration equal to 'speed' parameter.
| |
swiper.slideToClosest(speed, runCallbacks) | Reset swiper position to closest slide/snap point for the duration equal to 'speed' parameter.
| |
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
| |
swiper.slidesPerViewDynamic() | Get dynamically calculated amount of slides per view, useful only when slidesPerView set to | |
swiper.translateTo(translate, speed, runCallbacks, translateBounds) | Animate custom css3 transform's translate value for swiper wrapper
| |
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
| |
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:
在滑动条初始化时使用 on
参数:
¥Using on
parameter on swiper initialization:
const swiper = new Swiper('.swiper', {
// ...
on: {
init: function () {
console.log('swiper initialized');
},
},
});
在滑动条初始化后使用 on
方法。
¥Using on
method after swiper initialization.
const swiper = new Swiper('.swiper', {
// ...
});
swiper.on('slideChange', function () {
console.log('slide changed');
});
this
keyword within event handler always points to Swiper instanceName | Arguments | Description |
---|---|---|
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 |
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 |
fromEdge | (swiper) | Event will be fired when Swiper goes from beginning or end position |
init | (swiper) | Fired right after Swiper initialization.
|
lock | (swiper) | Event will be fired when swiper is locked (when |
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 |
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 |
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 |
touchMove | (swiper, event) | Event will be fired when user touch and move finger over Swiper. Receives |
touchMoveOpposite | (swiper, event) | Event will be fired when user touch and move finger over Swiper in direction opposite to direction parameter. Receives |
touchStart | (swiper, event) | Event will be fired when user touch Swiper. Receives |
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 |
update | (swiper) | Event will be fired after swiper.update() call |
¥Modules
¥Navigation Parameters
Name | Type | Default | Description |
---|---|---|---|
disabledClass | string | 'swiper-button-disabled' | CSS class name added to navigation button when it becomes disabled |
enabled | boolean | Boolean property to use with breakpoints to enable/disable navigation on certain breakpoints | |
string | 'swiper-button-hidden' | CSS class name added to navigation button when it becomes hidden | |
hideOnClick | boolean | false | Toggle navigation buttons visibility after click on Slider's container |
lockClass | string | 'swiper-button-lock' | CSS class name added to navigation button when it is disabled |
navigationDisabledClass | string | 'swiper-navigation-disabled' | CSS class name added on swiper container when navigation is disabled by breakpoint |
nextEl | any | null | String with CSS selector or HTML element of the element that will work like "next" button after click on it |
prevEl | any | null | String with CSS selector or HTML element of the element that will work like "prev" button after click on it |
¥Navigation Methods
Properties | ||
---|---|---|
swiper.nextEl | HTMLElement | HTMLElement of "next" navigation button |
swiper.prevEl | HTMLElement | HTMLElement of "previous" navigation button |
Methods | ||
swiper.destroy() | Destroy navigation | |
swiper.init() | Initialize navigation | |
swiper.update() | Update navigation buttons state (enabled/disabled) |
¥Navigation Events
Name | Arguments | Description |
---|---|---|
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 |
¥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 Parameters
Name | Type | Default | Description |
---|---|---|---|
bulletActiveClass | string | 'swiper-pagination-bullet-active' | CSS class name of currently active pagination bullet |
bulletClass | string | 'swiper-pagination-bullet' | CSS class name of single pagination bullet |
bulletElement | string | 'span' | Defines which HTML tag will be used to represent single pagination bullet. Only for |
clickable | boolean | false | If |
clickableClass | string | 'swiper-pagination-clickable' | CSS class name set to pagination when it is clickable |
currentClass | string | 'swiper-pagination-current' | CSS class name of the element with currently active index in "fraction" pagination |
dynamicBullets | boolean | false | 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. |
dynamicMainBullets | number | 1 | The number of main bullets visible when |
el | any | null | String with CSS selector or HTML element of the container with pagination |
enabled | boolean | Boolean property to use with breakpoints to enable/disable pagination on certain breakpoints | |
formatFractionCurrent | function(number) | format fraction pagination current number. Function receives current number, and you need to return formatted value | |
formatFractionTotal | function(number) | format fraction pagination total number. Function receives total number, and you need to return formatted value | |
string | 'swiper-pagination-hidden' | CSS class name of pagination when it becomes inactive | |
hideOnClick | boolean | true | Toggle (hide/show) pagination container visibility after click on Slider's container |
horizontalClass | string | 'swiper-pagination-horizontal' | CSS class name set to pagination in horizontal Swiper |
lockClass | string | 'swiper-pagination-lock' | CSS class name set to pagination when it is disabled |
modifierClass | string | 'swiper-pagination-' | The beginning of the modifier CSS class name that will be added to pagination depending on parameters |
paginationDisabledClass | string | 'swiper-pagination-disabled' | CSS class name added on swiper container and pagination element when pagination is disabled by breakpoint |
progressbarFillClass | string | 'swiper-pagination-progressbar-fill' | CSS class name of pagination progressbar fill element |
progressbarOpposite | boolean | false | Makes pagination progressbar opposite to Swiper's |
progressbarOppositeClass | string | 'swiper-pagination-progressbar-opposite' | CSS class name of pagination progressbar opposite |
renderBullet | function(index, className) | This parameter allows totally customize pagination bullets, you need to pass here a function that accepts
| |
renderCustom | function(swiper, current, total) | This parameter is required for
| |
renderFraction | function(currentClass, totalClass) | This parameter allows to customize "fraction" pagination html. Only for
| |
renderProgressbar | function(progressbarFillClass) | This parameter allows to customize "progress" pagination. Only for
| |
totalClass | string | '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 |
verticalClass | string | 'swiper-pagination-vertical' | CSS class name set to pagination in vertical Swiper |
¥Pagination Methods
Properties | ||
---|---|---|
swiper.bullets | HTMLElement[] | Array of pagination bullets HTML elements. To get specific slide HTMLElement use |
swiper.el | HTMLElement | 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
Name | Arguments | Description |
---|---|---|
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 |
¥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 Parameters
Name | Type | Default | Description |
---|---|---|---|
dragClass | string | 'swiper-scrollbar-drag' | Scrollbar draggable element CSS class |
dragSize | number | 'auto' | 'auto' | Size of scrollbar draggable element in px |
draggable | boolean | false | Set to |
el | any | null | String with CSS selector or HTML element of the container with scrollbar. |
enabled | boolean | Boolean property to use with breakpoints to enable/disable scrollbar on certain breakpoints | |
hide | boolean | true | Hide scrollbar automatically after user interaction |
horizontalClass | string | 'swiper-scrollbar-horizontal' | CSS class name set to scrollbar in horizontal Swiper |
lockClass | string | 'swiper-scrollbar-lock' | Scrollbar element additional CSS class when it is disabled |
scrollbarDisabledClass | string | 'swiper-scrollbar-disabled' | CSS class name added on swiper container and scrollbar element when scrollbar is disabled by breakpoint |
snapOnRelease | boolean | false | Set to |
verticalClass | string | 'swiper-scrollbar-vertical' | CSS class name set to scrollbar in vertical Swiper |
¥Scrollbar Methods
Properties | ||
---|---|---|
swiper.dragEl | HTMLElement | HTMLElement of Scrollbar draggable handler element |
swiper.el | HTMLElement | 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
Name | Arguments | Description |
---|---|---|
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 |
¥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 Parameters
Name | Type | Default | Description |
---|---|---|---|
delay | number | 3000 | 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 using
|
disableOnInteraction | boolean | true | Set to |
pauseOnMouseEnter | boolean | false | When enabled autoplay will be paused on pointer (mouse) enter over Swiper container. |
reverseDirection | boolean | false | Enables autoplay in reverse direction |
stopOnLastSlide | boolean | false | Enable this parameter and autoplay will be stopped when it reaches last slide (has no effect in loop mode) |
waitForTransition | boolean | true | 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.paused | boolean | Whether autoplay is paused |
swiper.running | boolean | Whether autoplay enabled and running |
swiper.timeLeft | number | 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
Name | Arguments | Description |
---|---|---|
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 Parameters
Name | Type | Default | Description |
---|---|---|---|
enabled | boolean | false | Whether the free mode is enabled |
minimumVelocity | number | 0.02 | Minimum touchmove-velocity required to trigger free mode momentum |
momentum | boolean | true | If enabled, then slide will keep moving for a while after you release it |
momentumBounce | boolean | true | Set to |
momentumBounceRatio | number | 1 | Higher value produces larger momentum bounce effect |
momentumRatio | number | 1 | Higher value produces larger momentum distance after you release slider |
momentumVelocityRatio | number | 1 | Higher value produces larger momentum velocity after you release slider |
sticky | boolean | false | Set to enabled to enable snap to slides positions in free mode |
¥Grid Parameters
Name | Type | Default | Description |
---|---|---|---|
fill | 'row' | 'column' | 'column' | Can be
|
rows | number | 1 | Number of slides rows, for multirow layout |
操作模块添加了实用的 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:
| |
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:
| |
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:
| |
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.
|
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
Name | Type | Default | Description |
---|---|---|---|
enabled | boolean | false | Enable, if you want to use "parallaxed" elements inside of slider |
自版本 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>
请确保将 effect
参数设置为 'fade'
才能使其正常工作。
¥Be sure to have the effect
param set to 'fade'
in order for this to work.
crossFade
should be set to true
in order to avoid seeing content behind or underneath.¥Fade Effect Parameters
Name | Type | Default | Description |
---|---|---|---|
crossFade | boolean | false | Enables slides cross fade |
请确保将 effect
参数设置为 'coverflow'
才能使其正常工作。
¥Be sure to have the effect
param set to 'coverflow'
in order for this to work.
¥Coverflow Effect Parameters
Name | Type | Default | Description |
---|---|---|---|
depth | number | 100 | Depth offset in px (slides translate in Z axis) |
modifier | number | 1 | Effect multiplier |
rotate | number | 50 | Slide rotate in degrees |
scale | number | 1 | Slide scale effect |
slideShadows | boolean | true | Enables slides shadows |
stretch | number | 0 | Stretch space between slides (in px) |
请确保将 effect
参数设置为 'flip'
才能使其正常工作。
¥Be sure to have the effect
param set to 'flip'
in order for this to work.
¥Flip Effect Parameters
Name | Type | Default | Description |
---|---|---|---|
limitRotation | boolean | true | Limit edge slides rotation |
slideShadows | boolean | true | Enables slides shadows |
请确保将 effect
参数设置为 'cube'
才能使其正常工作。
¥Be sure to have the effect
param set to 'cube'
in order for this to work.
¥Cube Effect Parameters
Name | Type | Default | Description |
---|---|---|---|
shadow | boolean | true | Enables main slider shadow |
shadowOffset | number | 20 | Main shadow offset in px |
shadowScale | number | 0.94 | Main shadow scale ratio |
slideShadows | boolean | true | Enables slides shadows |
请确保将 effect
参数设置为 'cards'
才能使其正常工作。
¥Be sure to have the effect
param set to 'cards'
in order for this to work.
¥Cards Effect Parameters
Name | Type | Default | Description |
---|---|---|---|
perSlideOffset | number | 8 | Offset distance per slide (in px) |
perSlideRotate | number | 2 | Rotate angle per slide (in degrees) |
rotate | boolean | true | Enables cards rotation |
slideShadows | boolean | true | Enables slides shadows |
请确保将 effect
参数设置为 'creative'
才能使其正常工作。
¥Be sure to have the effect
param set to 'creative'
in order for this to work.
¥Creative Effect Parameters
Name | Type | Default | Description |
---|---|---|---|
limitProgress | number | 1 | Limit progress/offset to amount of side slides. If |
next | CreativeEffectTransform | Next slide transformations.
| |
perspective | boolean | true | Enable this parameter if your custom transforms require 3D transformations ( |
prev | CreativeEffectTransform | Previous slide transformations. Accepts object of the following type:
| |
progressMultiplier | number | 1 | Allows to multiply slides transformations and opacity. |
shadowPerProgress | boolean | false | Splits shadow "opacity" per slide based on |
除了 控制器 组件外,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
Name | Type | Default | Description |
---|---|---|---|
autoScrollOffset | number | 0 | 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 |
multipleActiveThumbs | boolean | true | When enabled multiple thumbnail slides may get activated |
slideThumbActiveClass | string | 'swiper-slide-thumb-active' | Additional class that will be added to activated thumbs swiper slide |
swiper | any | null | Swiper instance of swiper used as thumbs or object with Swiper parameters to initialize thumbs swiper |
thumbsContainerClass | string | 'swiper-thumbs' | Additional class that will be added to thumbs swiper |
¥Thumbs Methods
Properties | ||
---|---|---|
swiper.swiper | any | Swiper instance of thumbs swiper |
Methods | ||
swiper.init() | Initialize thumbs | |
swiper.update(initial) | Update thumbs |
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.
默认情况下,它会缩放 img
、picture
或 canvas
元素之一。如果你想对其他自定义元素进行缩放,只需将 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
Name | Type | Default | Description |
---|---|---|---|
containerClass | string | 'swiper-zoom-container' | CSS class name of zoom container |
limitToOriginalSize | boolean | false | When set to true, the image will not be scaled past 100% of its original size |
maxRatio | number | 3 | Maximum image zoom multiplier |
minRatio | number | 1 | Minimal image zoom multiplier |
panOnMouseMove | boolean | false | When set to true, a zoomed in image will automatically pan while moving the mouse over the image |
toggle | boolean | true | Enable/disable zoom-in by slide's double tap |
zoomedSlideClass | string | 'swiper-slide-zoomed' | CSS class name of zoomed in container |
¥Zoom Methods
Properties | ||
---|---|---|
swiper.enabled | boolean | Whether the zoom module is enabled |
swiper.scale | number | 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
Name | Arguments | Description |
---|---|---|
zoomChange | (swiper, scale, imageEl, slideEl) | Event will be fired on zoom change |
¥Keyboard Control Parameters
Name | Type | Default | Description |
---|---|---|---|
enabled | boolean | false | Set to |
onlyInViewport | boolean | true | When enabled it will control sliders that are currently in viewport |
pageUpDown | boolean | true | When enabled it will enable keyboard navigation by Page Up and Page Down keys |
¥Keyboard Control Methods
Properties | ||
---|---|---|
swiper.enabled | boolean | Whether the keyboard control is enabled |
Methods | ||
swiper.disable() | Disable keyboard control | |
swiper.enable() | Enable keyboard control |
¥Keyboard Events
Name | Arguments | Description |
---|---|---|
keyPress | (swiper, keyCode) | Event will be fired on key press |
¥Mousewheel Control Parameters
Name | Type | Default | Description |
---|---|---|---|
enabled | boolean | false | Set to |
eventsTarget | any | 'container' | String with CSS selector or HTML element of the container accepting mousewheel events. By default it is swiper |
forceToAxis | boolean | false | Set to |
invert | boolean | false | Set to |
noMousewheelClass | string | 'swiper-no-mousewheel' | Scrolling on elements with this class will be ignored |
releaseOnEdges | boolean | false | Set to |
sensitivity | number | 1 | Multiplier of mousewheel data, allows to tweak mouse wheel sensitivity |
thresholdDelta | null | number | null | Minimum mousewheel scroll delta to trigger swiper slide change |
thresholdTime | null | number | null | Minimum mousewheel scroll time delta (in ms) to trigger swiper slide change |
¥Mousewheel Control Methods
Properties | ||
---|---|---|
swiper.enabled | boolean | Whether the mousewheel control is enabled |
Methods | ||
swiper.disable() | Disable mousewheel control | |
swiper.enable() | Enable mousewheel control |
¥Mousewheel Events
Name | Arguments | Description |
---|---|---|
scroll | (swiper, event) | Event will be fired on mousewheel scroll |
虚拟幻灯片模块允许在 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.
slidesPerView: 'auto'
¥Virtual Slides Parameters
Name | Type | Default | Description |
---|---|---|---|
addSlidesAfter | number | 0 | Increases amount of pre-rendered slides after active slide |
addSlidesBefore | number | 0 | Increases amount of pre-rendered slides before active slide |
cache | boolean | true | Enables DOM cache of rendering slides html elements. Once they are rendered they will be saved to cache and reused from it. |
enabled | boolean | false | Whether the virtual slides are enabled |
renderExternal | function(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
| |
renderExternalUpdate | boolean | true | 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 |
renderSlide | function(slide, index) | Function to render slide. As an argument it accepts current slide item for | |
slides | T[] | [] | Array with slides |
¥Virtual Slides Methods
Properties | ||
---|---|---|
swiper.cache | object | Object with cached slides HTML elements |
swiper.from | number | Index of first rendered slide |
swiper.slides | T[] | Array with slide items passed by |
swiper.to | number | Index of last rendered slide |
Methods | ||
swiper.appendSlide(slide) | Append slide.
| |
swiper.prependSlide(slide) | Prepend slide.
| |
swiper.removeAllSlides() | Remove all slides
| |
swiper.removeSlide(slideIndexes) | Remove specific slide or slides.
| |
swiper.update(force) | Update virtual slides state |
¥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 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
Name | Type | Default | Description |
---|---|---|---|
getSlideIndex | function(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) | |
replaceState | boolean | false | Works in addition to hashnav to replace current url state with the new one instead of adding it to history |
watchState | boolean | false | Set to |
¥Hash Navigation Events
Name | Arguments | Description |
---|---|---|
hashChange | (swiper) | Event will be fired on window hash change |
hashSet | (swiper) | Event will be fired when swiper updates the hash |
¥History Navigation Parameters
Name | Type | Default | Description |
---|---|---|---|
enabled | boolean | false | Enables History Plugin. |
keepQuery | boolean | false | Keep query parameters when changing browser url. |
key | string | 'slides' | Url key for slides |
replaceState | boolean | false | Works in addition to hashnav or history to replace current url state with the new one instead of adding it to history |
root | string | '' | Swiper page root, useful to specify when you use Swiper history mode not on root website page. For example can be |
¥Controller Parameters
Name | Type | Default | Description |
---|---|---|---|
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). |
control | any | 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 | |
inverse | boolean | false | Set to |
¥Controller Methods
Properties | ||
---|---|---|
swiper.control | any | Pass here another Swiper instance or array with Swiper instances that should be controlled by this Swiper |
¥Accessibility Parameters
Name | Type | Default | Description |
---|---|---|---|
containerMessage | null | string | null | Message for screen readers for outer swiper container |
containerRole | null | string | null | Value of the "role" attribute to be set on the swiper container |
containerRoleDescriptionMessage | null | string | null | Message for screen readers describing the role of outer swiper container |
enabled | boolean | true | Enables A11y |
firstSlideMessage | string | 'This is the first slide' | Message for screen readers for previous button when swiper is on first slide |
id | null | string | number | null | Value of |
itemRoleDescriptionMessage | null | string | null | Message for screen readers describing the role of slide element |
lastSlideMessage | string | 'This is the last slide' | Message for screen readers for next button when swiper is on last slide |
nextSlideMessage | string | 'Next slide' | Message for screen readers for next button |
notificationClass | string | 'swiper-notification' | CSS class name of A11y notification |
paginationBulletMessage | string | 'Go to slide {{index}}' | Message for screen readers for single pagination bullet |
prevSlideMessage | string | 'Previous slide' | Message for screen readers for previous button |
scrollOnFocus | boolean | true | Enables scrolling to the slide that has been focused |
slideLabelMessage | string | '{{index}} / {{slidesLength}}' | Message for screen readers describing the label of slide element |
slideRole | string | 'group' | Value of swiper slide |
¥Custom Build
你有两种方法可以创建自定义版本的 Swiper。
¥You have two options of making custom version of Swiper.
¥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
¥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:
下载并解压 Swiper GitHub 仓库 到本地文件夹
¥Download and unzip Swiper GitHub repository to local folder
安装 Node.js(如果尚未安装)
¥Install Node.js (if not installed)
现在,我们需要安装所需的依赖。前往下载并解压的 Swiper 代码库所在的文件夹,并在终端中执行:
¥Now, we need to install required dependencies. Go to the folder with downloaded and unzipped Swiper repository and execute in terminal:
$ npm install
打开 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',
],
};
现在,我们可以构建自定义版本的 Swiper 了:
¥Now, we are ready to build custom version of Swiper:
$ npm run build:prod
就是这样。生成的 CSS 和 JS 文件及其压缩版本将在 dist/
文件夹。
¥That is all. Generated CSS and JS files and their minified versions will be available in dist/
folder.
¥TypeScript Definitions
Swiper 是完全类型化的,它导出 Swiper
和 SwiperOptions
类型:
¥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.