最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to pause autoplay in react swiper on hover? - Stack Overflow

programmeradmin2浏览0评论

I'm trying to figure out how can i pause autoplay on swiper when i hover but i cannot find it anywhere

<Swiper
                    spaceBetween={0}
                    navigation={{
                        prevEl: navigationPrevRef.current,
                        nextEl: navigationNextRef.current,
                    }}
                    autoplay={{
                        delay: 3000,
                        pauseOnMouseEnter: true,
                    }}
>

I'm trying to figure out how can i pause autoplay on swiper when i hover but i cannot find it anywhere

<Swiper
                    spaceBetween={0}
                    navigation={{
                        prevEl: navigationPrevRef.current,
                        nextEl: navigationNextRef.current,
                    }}
                    autoplay={{
                        delay: 3000,
                        pauseOnMouseEnter: true,
                    }}
>
Share Improve this question asked Jan 28, 2022 at 18:35 Burhan AliBurhan Ali 1291 silver badge8 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

In this case, all you should need is the pauseOnMouseEnter attribute set to true, like you have. The issue seems to be because you don't have the autoplay module connected.

You should have imported these:

import { Autoplay, Navigation } from 'swiper'
import 'swiper/css'
import 'swiper/css/navigation'

Now that Autoplay has been imported, we need connect it to the individual Swiper:

<Swiper
  // spaceBetween can be removed if you have it set to 0
  // spaceBetween={0}
  navigation={{
    prevEl: navigationPrevRef.current,
    nextEl: navigationNextRef.current,
  }}
  autoplay={{
    disableOnInteraction: false, // Optional, but remended
    delay: 3000
    pauseOnMouseEnter: true,
  }}
  modules={[ Autoplay, Navigation ]}
>

I hope that helps. Swiper can be a headache. Their documentation is very in depth.

So I found a work around hope it helps those who are still facing this issue. Just give a ref to your swpier use onMouseEnter and onMouseLeave on your parent div

import {useRef} from "react";

    const swiperRefLocal = useRef()

    const handleMouseEnter = () => {
        swiperRefLocal?.current?.swiper?.autoplay?.stop()
    };

    const handleMouseLeave = () => {
        swiperRefLocal?.current?.swiper?.autoplay?.start()
    };

<div onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave}>
   <Swiper
                    spaceBetween={0}
                    ref={swiperRefLocal}
                    navigation={{
                        prevEl: navigationPrevRef.current,
                        nextEl: navigationNextRef.current,
                    }}
                    autoplay={{
                        delay: 3000,
                    }}
>
</div>
发布评论

评论列表(0)

  1. 暂无评论