提问者:小点点

停止滑动鼠标自动播放进入和开始自动播放鼠标离开


如何在鼠标进入时停止滑动自动播放和在鼠标离开时开始自动播放?我尝试了.stopautoplay().startautoplay()函数,但对我无效。

谢谢。这是代码。我面临控制台错误

未捕获的TypeError:swiper.StartautoPlay不是函数

 var swiper = new Swiper('.swiper-container', {
    pagination: '.swiper-pagination',
    paginationClickable: true,
    nextButton: '.swiper-button-next',
    prevButton: '.swiper-button-prev',
    spaceBetween: 0,
    loop: true,
    effect: 'slide',
    longSwipes: true,
    autoplay:2000,
    autoplayDisableOnInteraction:true,
});


$(".swiper-container").mouseenter(function(){
    swiper.stopAutoplay();
});

$(".swiper-container").mouseleave(function(){
    swiper.startAutoplay();
});

共1个答案

匿名用户

您需要使用disableoninteraction:true选项,而不是自己绑定事件(参见此处获取文档)。

您还可以使用以下选项进行自动播放开始和停止

>

  • swiper.autoplay.start();

    swiper.autoplay.stop();

    编辑

    您的错误在于如何获取Swiper的实例。见下面的演示

    null

    $(document).ready(function() {
      new Swiper('.swiper-container', {
        speed: 400,
        spaceBetween: 100,
        autoplay: true,
        disableOnInteraction: true,
      });
      var mySwiper = document.querySelector('.swiper-container').swiper
    
      $(".swiper-container").mouseenter(function() {
        mySwiper.autoplay.stop();
        console.log('slider stopped');
      });
    
      $(".swiper-container").mouseleave(function() {
        mySwiper.autoplay.start();
        console.log('slider started again');
      });
    });
    .swiper-slide {
      text-align: center;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.0.5/js/swiper.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.0.5/css/swiper.css" rel="stylesheet" />
    <!-- Slider main container -->
    <div class="swiper-container">
      <!-- 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 class="swiper-slide">Slide 4</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>