Amaze UI Plugin

Amaze UI Swiper

Amaze UI styled swiper

Star Fork Download

Amaze UI Swiper API


基本使用

HTML 结构

<!-- Slider 主容器,必需 -->
<div class="swiper-container">

  <!-- slides 容器,必需 -->
  <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>

  <!-- 分页容器,可选 -->
  <div class="swiper-pagination"></div>

  <!-- 上下翻页箭头,可选 -->
  <div class="swiper-button-prev"></div>
  <div class="swiper-button-next"></div>

  <!-- 滚动条容器,可选 -->
  <div class="swiper-scrollbar"></div>
</div>

初始化

// jQuery 方式初始化
$('#container').swiper([options]);


// 或者构造函数方式初始化
var mySwiper = new Swiper(swiperContainer[, options])

// `swiperContainer` - 必需,HTMLElement 或者 CSS 选择符字符串
// options - object

选项列表

没有翻译的为不太常用的选项。

选项 类型 默认值 描述
initialSlide number 0 初始 slide 索引值
direction string 'horizontal' 滚动方式,horizontal 或者 vertical
speed number 300 滚动速度 ms
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
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
width number 设置 Swiper 宽度 px,一般用于初始化隐藏的 swiper。
height number 设置 Swiper 高度 px
Autoplay - 自动播放相关
autoplay number - 自动播放间隔时间 ms,设置此项才会启用自动播放功能。
autoplayDisableOnInteraction boolean true 用户交互时停止自动播放
Progress
watchSlidesProgress boolean false Enable this feature to calculate each slides progress
watchSlidesVisibility boolean false watchSlidesProgress should be enabled. Enable this option and slides that are in viewport will have additional visible class
Freemode
freeMode boolean false If true then slides will not have fixed positions
freeModeMomentum boolean true If true, then slide will keep moving for a while after you release it
freeModeMomentumRatio number 1 Higher value produces larger momentum distance after you release slider
freeModeMomentumBounce boolean true Set to false if you want to disable momentum bounce in free mode
freeModeMomentumBounceRatio number 1 Higher value produces larger momentum bounce effect
freeModeSticky boolean false Set to true to enable snap to slides positions in free mode
Effects - 动画效果
effect string 'slide' 'slide' | 'fade' | 'cube' | 'coverflow'
fade object fade: { crossFade: false } Fade 效果参数
cube object cube: { slideShadows: true, shadow: true, shadowOffset: 20, shadowScale: 0.94 } Cube 动画参数,建议禁用阴影以提高性能。
coverflow object coverflow: { rotate: 50, stretch: 0, depth: 100, modifier: 1, slideShadows : true } Coverflow 动画参数,建议禁用阴影以提高性能。
Parallax - 视差滚动
parallax boolean false 开启此项以使用视差滚动效果
Slides grid
spaceBetween number 0 slide 间距
slidesPerView number or 'auto' 1

每一屏显示的 slide 数量

If you use it with "auto" value and along with loop: true then you need to specify loopedSlides parameter with amount of slides to loop (duplicate)

slidesPerView: 'auto' is currently not compatible with multirow mode, when slidesPerColumn > 1

slidesPerColumn number 1 每列显示的 slide 数量
slidesPerColumnFill string 'column' Could be 'column' or 'row'. Defines how slides should fill rows, by column or by row
slidesPerGroup number 1 Set numbers of slides to define and enable group sliding. Useful to use with slidesPerView > 1
centeredSlides boolean false If true, then active slide will be centered, not always on the left side.
Grab Cursor
grabCursor boolean false This option may a little improve desktop usability. If true, user will see the "grab" cursor when hover on Swiper
Touches - 触控
touchRatio number 1 Touch ration
touchAngle number 45 Allowable angle (in degrees) to trigger touch move
simulateTouch boolean true If true, Swiper will accept mouse events like touch events (click and drag to change slides)
shortSwipes boolean true Set to false if you want to disable short swipes
longSwipes boolean true Set to false if you want to disable long swipes
longSwipesRatio number 0.5 Ratio to trigger swipe to next/previous slide during long swipes
longSwipesMs number 300 Minimal duration (in ms) to trigger swipe to next/previous slide during long swipes
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
onlyExternal boolean false If true, then the only way to switch the slide is use of external API functions like slidePrev or slideNext
threshold number 0 Threshold value in px. If "touch distance" will be lower than this value then swiper will not move
touchMoveStopPropagation boolean true If enabled, then propagation of "touchmove" will be stopped
Touch Resistance
resistance boolean true Set to false if you want to disable resistant bounds
resistanceRatio number 0.85 This option allows you to control resistance ratio
Clicks
preventClicks boolean true Set to true to prevent accidental unwanted clicks on links during swiping
preventClicksPropagation boolean true Set to true to stop clicks event propagation on links during swiping
slideToClickedSlide boolean false Set to true and click on any slide will produce transition to this slide
Swiping / No swiping
allowSwipeToPrev boolean true Set to false to disable swiping to previous slide direction (to left or top)
allowSwipeToNext boolean true Set to false to disable swiping to next slide direction (to right or bottom)
noSwiping boolean true Set to false to disable swiping to next slide direction (to right or bottom)
noSwipingClass string 'swiper-no-swiping' If true, then you can add noSwipingClass class to swiper's slide to prevent/disable swiping on this element
swipeHandler string / HTMLElement null String with CSS selector or HTML element of the container with pagination that will work as only available handler for swiping
Pagination
pagination string / HTMLElement null String with CSS selector or HTML element of the container with pagination
paginationHide boolean true Toggle (hide/true) pagination container visibility when click on Slider's container
paginationClickable boolean false If true then clicking on pagination button will cause transition to appropriate slide
paginationBulletRender(index, className) function null 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).

For example, with this code, we can add slide number into pagination bullet:

var swiper = new Swiper('.swiper-container', {
  //...
  paginationBulletRender: function (index, className) {
  return '<span class="' + className + '">' + (index + 1) + '</span>';
  }
  });              
Navigation Buttons
nextButton string / HTMLElement null String with CSS selector or HTML element of the element that will work like "next" button after click on it
prevButton string / HTMLElement null String with CSS selector or HTML element of the element that will work like "prev" button after click on it
Accessibility
a11y boolean false Option to enable keyboard accessibility to provide foucsable navigation buttons and basic ARIA for screen readers
prevSlideMessage string 'Previous slide' Message for screen readers for previous button
nextSlideMessage string 'Next slide' Message for screen readers for next button
firstSlideMessage string 'This is the first slide' Message for screen readers for previous button when swiper is on first slide
lastSlideMessage string 'This is the last slide' Message for screen readers for previous button when swiper is on last slide
Scollbar
scrollbar string / HTMLElement null String with CSS selector or HTML element of the container with scrollbar.
scrollbarHide boolean true Hide scrollbar automatically after user interaction
Keyboard / Mousewheel
keyboardControl boolean false Set to true to enable navigation through slides using keyboard right and left (for horizontal mode), top and borrom (for vertical mode) keyboard arrows
mousewheelControl boolean false Set to true to enable navigation through slides using mouse wheel
mousewheelForceToAxis boolean false 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.
mousewheelReleaseOnEdges boolean false 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)
mousewheelInvert boolean false Set to true to invert sliding direction
Hash Navigation
hashnav boolean false Set to true to enable hash url navigation to for slides
Images
preloadImages boolean true When enabled Swiper will force to load all images
updateOnImagesReady boolean true When enabled Swiper will be reinitialized after all inner images (<img> tags) are loaded. Required preloadImages: true
lazyLoading boolean false Set to "true" to enable images lazy loading. Note that preloadImages should be disabled
lazyLoadingInPrevNext boolean false Set to "true" to enable lazy loading for the closest slides images (for previous and next slide images)
lazyLoadingOnTransitionStart boolean false By default, Swiper will load lazy images after transition to this slide, so you may enable this parameter if you need it to start loading of new image in the beginning of transition
Loop
loop boolean false

Set to true to enable continuous loop mode

If you use it along with slidesPerView: 'auto' then you need to specify loopedSlides parameter with amount of slides to loop (duplicate)

loopAdditionalSlides number 0 Addition number of slides that will be cloned after creating of loop
loopedSlides number null If you use slidesPerView:'auto' with loop mode you should tell to Swiper how many slides it should loop (duplicate) using this parameter
Controller
control [Swiper Instance] undefined Pass here another Swiper instance or array with Swiper instances that should be controlled by this Swiper
controlInverse boolean false Set to true and controlling will be in inverse direction
Observer
observer boolean false 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)
observeParents boolean false Set to true if you also need to watch Mutations for Swiper parent elements
Callbacks
runCallbacksOnInit boolean true Run on[Transition/SlideChange][Start/End] callbacks on swiper initialization. Such callbacks will be fired on initialization in case of your initialSlide is not 0, or you use loop mode
onInit(swiper) function Callback function, will be executed right after Swiper initialization
onSlideChangeStart(swiper) function Callback function, will be executed in the beginning of animation to other slide (next or previous). Receives swiper instance as an argument.
onSlideChangeEnd(swiper) function Callback function, will be executed after animation to other slide (next or previous). Receives slider instance as an argument.
onTransitionStart(swiper) function Callback function, will be executed in the beginning of transition. Receives swiper instance as an argument.
onTransitionEnd(swiper) function Callback function, will be executed after transition. Receives slider instance as an argument.
onTouchStart(swiper, event) function Callback function, will be executed when user touch Swiper. Receives swiper instance and 'touchstart' event as an arguments.
onTouchMove(swiper, event) function Callback function, will be executed when user touch and move finger over Swiper. Receives swiper instance and 'touchmove' event as an arguments.
onTouchMoveOpposite(swiper, event) function Callback function, will be executed when user touch and move finger over Swiper in direction opposite to direction parameter. Receives swiper instance and 'touchmove' event as an arguments.
onSliderMove(swiper, event) function Callback function, will be executed when user touch and move finger over Swiper and move it. Receives swiper instance and 'touchmove' event as an arguments.
onTouchEnd(swiper, event) function Callback function, will be executed when user release Swiper. Receives swiper instance and 'touchend' event as an arguments.
onClick(swiper, event) function Callback function, will be executed when user click/tap on Swiper after 300ms delay. Receives swiper instance and 'touchend' event as an arguments.
onTap(swiper, event) function Callback function, will be executed when user click/tap on Swiper. Receives swiper instance and 'touchend' event as an arguments.
onDoubleTap(swiper, event) function Callback function, will be executed when user double tap on Swiper's container. Receives swiper instance and 'touchend' event as an arguments
onImagesReady(swiper) function Callback function, will be executed right after all inner images are loaded. updateOnImagesReady should be also enabled
onProgress(swiper, progress) function Callback function, will be executed when Swiper progress is changed, as second arguments it receives progress that is always from 0 to 1
onReachBeginning(swiper) function Callback function, will be executed when Swiper reach its beginning (initial position)
onReachEnd(swiper) function Callback function, will be executed when Swiper reach last slide
onDestroy(swiper) function Callback function, will be executed when you destroy Swiper
onSetTranslate(swiper, translate) function Callback function, will be executed when swiper's wrapper change its position. Receives swiper instance and current translate value as an arguments
onSetTransition(swiper, transition) function Callback function, will be executed everytime when swiper starts animation. Receives swiper instance and current transition duration (in ms) as an arguments
onAutoplayStart(swiper) function Callback function, will be executed when when autoplay started
onAutoplayStop(swiper) function Callback function, will be executed when when autoplay stopped
onLazyImageLoad(swiper, slide, image) function Callback function, will be executed in the beginning of lazy loading of image
onLazyImageReady(swiper, slide, image) function Callback function, will be executed when lazy loading image will be loaded
Namespace
slideClass string 'swiper-slide' CSS class name of slide
slideActiveClass string 'swiper-slide-active' CSS class name of currently active slide
slideVisibleClass string 'swiper-slide-visible' CSS class name of currently visible slide
slideDuplicateClass string 'swiper-slide-duplicate' CSS class name of slide duplicated by loop mode
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
wrapperClass string 'swiper-wrapper' CSS class name of slides' wrapper
bulletClass string 'swiper-pagination-bullet' CSS class name of single pagination bullet
bulletActiveClass string 'swiper-pagination-bullet-active' CSS class name of currently active pagination bullet
paginationHiddenClass string 'swiper-pagination-hidden' CSS class name of pagination when it becomes inactive
buttonDisabledClass string 'swiper-button-disabled' CSS class name of next/prev button when it becomes disabled

方法和属性

所有方法和属性都可以通过 $('#mySwiper').swiper('xxx') 的方式调用(读取),如

// 获取 swiper 的所有参数
$('#demo1').swiper('params');
属性
.params Swiper 初始化参数
.container 主容器,Dom7/jQuery 元素对象,可以通过 .container[0] 获取原生 HTMLElement 对象
.wrapper Slides 容器,Dom7/jQuery 元素对象,可以通过 .wrapper[0] 获取原生 HTMLElement 对象
.slides 所有幻灯片 Dom7/jQuery 元素对象数组
.bullets 所有分页页码 Dom7/jQuery 元素对象数组
.width 容器宽度
.height 容器高度
.translate 当前变换(translate)值
.progress 滚动进度(当前幻灯片索引/幻灯片总数)
.activeIndex 当前幻灯片索引(loop 模式此值将不准确)
.previousIndex 上一张幻灯片索引
.isBeginning 是否位于初始位置
.isEnd 是否位于结束位置
.autoplaying 是否在自动播放
.animating 是否正在执行动画
.touches 包含以下属性的触控事件对象:
  • .touches.startX
  • .touches.startY
  • .touches.currentX
  • .touches.currentY
  • .touches.diff
.clickedIndex 最后点击的幻灯片索引
.clickedSlide 最后点击的幻灯片 (HTMLElement)
Methods
.slideNext(runCallbacks, speed); 切换到一下个 slide
  • runCallbacks - boolean - Set it to false (by default it is true) and transition will not produce onSlideChange callback functions. Optional
  • speed - number - transition duration (in ms). Optional
.slidePrev(runCallbacks, speed); 切换到上一个 slide
  • runCallbacks - boolean - Set it to false (by default it is true) and transition will not produce onSlideChange callback functions. Optional
  • speed - number - transition duration (in ms). Optional
.slideTo(index, speed, runCallbacks); 切换到索引编号为 `index` 的 slide
  • index - number - index number of slide
  • speed - number - transition duration (in ms). Optional
  • runCallbacks - boolean - Set it to false (by default it is true) and transition will not produce onSlideChange callback functions. Optional
.update(updateTranslate);

This method includes updateContainerSize, updateSlidesSize, updateProgress, updatePagination and updateClasses methods

You should call it after you add/remove slides manually, or after you hide/show it, or do any custom DOM modifications with Swiper

  • updateTranslate - boolean - Set it to true (by default it is false) to hard set/reset/update Swiper wrapper translate. It is useful if you use not default effect or scrollbar. Optional

This method also includes subcall of the following methods which you can use separately:

  • .updateContainerSize() - recalculate size of swiper container
  • .updateSlidesSize() - recalculate number of slides and their offsets. Useful after you add/remove slides with JavaScript
  • .updateProgress() - recalculate swiper progress
  • .updatePagination() - updates pagination layout and re-render bullets
  • .updateClasses() - update active/prev/next classes on slides and bullets
.onResize(); Swiper executes this method when you resize browser. It is almost the same as .update() but a bit softer, without hard setting translate
.detachEvents(); 移除所有事件处理函数
.attachEvents(); 绑定事件处理函数
.startAutoplay(); 开始自动播放
.stopAutoplay(); 停止自动播放
.destroy(deleteInstance, cleanupStyles); 销毁 Slide 实例:
  • deleteInstance - boolean - Set it to false (by default it is true) to not to delete Swiper instance
  • cleanupStyles - boolean - Set it to true (by default it is false) 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
.appendSlide(slides); 插入 slides,可以是 HTMLElement 或者 HTML 字符串 或者数组: .appendSlide('<div class="swiper-slide">Slide 10"</div>') .appendSlide([ '<div class="swiper-slide">Slide 10"</div>', '<div class="swiper-slide">Slide 11"</div>' ]);
.prependSlide(slides); 前置插入,参数同上。
.removeSlide(slideIndex); 移除指定索引的幻灯片,slideIndex 所以可以是一个数字或者包含多个索引的数组。 .removeSlide(0); //remove first slide
.removeSlide([0, 1]); //remove first and second slides
.removeAllSlides(); 移除所有幻灯片
.setWrapperTranslate(translate); Set custom css3 transform's translate value for swiper wrapper
.getWrapperTranslate(); Get current value of swiper wrapper css3 transform translate
.on(callback, handler) Add callback/event handler
.once(callback, handler) Add event/callback that will be executed only once
.off(callback) Remove all handlers for specified callback/event
.lockSwipeToNext()
.unlockSwipeToNext()
Disable (lock) / enable (unlock) ability to slide to the next slides
.lockSwipeToPrev()
.unlockSwipeToPrev()
Disable (lock) / enable (unlock) ability to slide to the previous slides
.lockSwipes()
.unlockSwipes()
Disable (lock) / enable (unlock) ability to change slides
.disableMousewheelControl(); Disable mousewheel control
.enableMousewheelControl(); Enable mousewheel control
.disableKeyboardControl(); Disable keyboard control
.enableKeyboardControl(); Enable keyboard control

进阶使用

Hash 切换

<div class="swiper-container" id="hashSwiper">
  <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>
$('#hashSwiper').swiper({
  // enable hash navigation
  hashnav: true
});

视差滚动

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

To enable parallax effects you need to init Swiper with passed parallax:true parameter and add data-swiper-parallax attribute on required elements

<div class="swiper-container">
  <!-- Parallax background element -->
  <div
    class="parallax-bg"
    style="background-image:url(http://lorempixel.com/900/600/nightlife/2/)"
    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>
    </div>
    ...
  </div>
</div>

All elements with specified data-swiper-parallax attribute will have parallax transition. This attribute may accept:

You can also pass custom transition duration for parallax elements by adding data-swiper-parallax-duration attribute.

懒加载

首先需要添加 Loader 容器,并在图片上添加 .swiper-lazy

<div class="swiper-container">
  <div class="swiper-wrapper">
    <div class="swiper-slide">
      <img data-src="path/to/picture-1.jpg" class="swiper-lazy">
      <div class="swiper-lazy-preloader"></div>
    </div>
    <div class="swiper-slide">
      <img data-src="path/to/picture-2.jpg" class="swiper-lazy">
      <div class="swiper-lazy-preloader"></div>
    </div>
    <div class="swiper-slide">
      <img data-src="path/to/picture-3.jpg" class="swiper-lazy">
      <div class="swiper-lazy-preloader"></div>
    </div>
  </div>
</div>
$('#mySwiper').swiper({
  // Disable preloading of all images
  preloadImages: false,

  // Enable lazy loading
  lazyLoading: true
});

事件 API

// Init Swiper
var mySwiper = new Swiper('.swiper-container');

// Later add callback
mySwiper.on('slideChangeStart', function () {
  console.log('slide change start');
});

// Add one more handler for this event
mySwiper.on('slideChangeStart', function () {
  console.log('slide change start 2');
});

// Add handler that will be executed only once
mySwiper.once('sliderMove', function () {
  console.log('slider moved');
});

// Somewhen later, remove all slideChangeStart handlers
mySwiper.off('slideChangeStart');

也可以使用下面的语法:

$('#mySwiper').swiper('on', 'slideChangeStart', function() {
  console.log('slide change start');
});
Amaze UI 微信
在微信上关注我们