多个 swiper 切换,隐藏后再显示无法自动轮播的解决办法

笔记心得 0

多个swiper间切换,swiper-container隐藏后再显示不会触发自动播放,必须手动滑动,才能被触发自动播放
官方文档中说是加入
observer:true,
observeParents:true,
可实际并没有效果。

多个 swiper 切换

经过尝试,用destroy销毁Swiper后再重新初始化,完美解决了此问题。

解决代码如下:

<div class="tab">
  <span>按钮一</span>
  <span>按钮二</span>
  <span>按钮三</span>
  <span>按钮四</span>
</div>
<div class="div">
  <div class="swiper-container">..............</div>
  <div class="swiper-container">..............</div>
  <div class="swiper-container">..............</div>
  <div class="swiper-container">..............</div>
</div>
<script>
  function swiperFn() {
    return new Swiper( '.div .swiper-container', {
      loop: true,
      autoplay: {
        delay: 3000,
        stopOnLastSlide: false,
        disableOnInteraction: false
      },
      // .............
    } )
  }
  var Myswiper = swiperFn()
  $( ".tab" ).on( 'click', 'span', function() {
    for ( var x in Myswiper ) {
      Myswiper[ x ].destroy( true, true ) // 销毁Swiper
    }
    $( this ).addClass( 'active' ).siblings().removeClass( 'active' )
    $( '.div .swiper-container' ).eq( $( this ).index() ).fadeIn( 300 ).siblings().fadeOut( 0 )
    Myswiper = swiperFn()
  } )
</script>


又尝试了另一种办法,切换时,先停止所有的自动播放,再开启当前显示层的swiper自动播放,也能解决

<div class="tab">
  <span>按钮一</span>
  <span>按钮二</span>
  <span>按钮三</span>
  <span>按钮四</span>
</div>
<div class="div">
  <div class="swiper-container">..............</div>
  <div class="swiper-container">..............</div>
  <div class="swiper-container">..............</div>
  <div class="swiper-container">..............</div>
</div>
<script>
  var Myswiper = Swiper( '.div .swiper-container', {
    loop: true,
    autoplay: {
      delay: 3000,
      stopOnLastSlide: false,
      disableOnInteraction: false
    },
    // .............
  } )

  $( ".tab" ).on( 'click', 'span', function() {
    for ( var x in Myswiper ) {
      Myswiper[ x ].autoplay.stop() // 停止所有的自动播放
    }
    Myswiper[ $( this ).index() ].autoplay.start() // 开始自动播放
    $( this ).addClass( 'active' ).siblings().removeClass( 'active' )
    $( '.div .swiper-container' ).eq( $( this ).index() ).fadeIn( 300 ).siblings().fadeOut( 0 )
  } )
</script>