如何在鼠标进入时停止滑动自动播放并在鼠标离开时开始自动播放?我尝试过 .stopAutoplay().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();
});

最佳答案

您需要使用选项 disableOnInteraction: true 而不是自己绑定(bind)事件,请参见此处的 documentation

您可以选择使用以下内容进行自动播放开始停止

  • swiper.autoplay.start();
  • swiper.autoplay.stop();

  • 编辑

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

    $(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>

    关于javascript - 鼠标进入时停止滑动自动播放并在鼠标离开时开始自动播放,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47238245/

    10-11 23:40