如何实现Swiper滑块hover时自动播放、移出时暂停?
实现Swiper鼠标悬停启动自动播放、移出暂停
要实现反向功能(鼠标悬停启动自动播放,移出暂停),可以通过监听鼠标事件并调用Swiper的自动播放控制方法来实现,具体方案如下:
方法一:外部事件监听
- 初始化Swiper时默认关闭自动播放:
const swiper = new Swiper('.swiper-container', { autoplay: false, // 初始不启动自动播放 disableOnInteraction: false, // 补充其他必要配置(如slidesPerView、loop等) });
- 给Swiper容器绑定鼠标事件:
const swiperEl = document.querySelector('.swiper-container'); // 鼠标悬停时启动自动播放 swiperEl.addEventListener('mouseenter', () => { swiper.autoplay.start(); }); // 鼠标移出时暂停自动播放 swiperEl.addEventListener('mouseleave', () => { swiper.autoplay.stop(); });
方法二:Swiper内置事件绑定
也可以直接在初始化配置里通过on选项绑定事件,代码更紧凑:
const swiper = new Swiper('.swiper-container', { autoplay: false, disableOnInteraction: false, // 补充其他必要配置 on: { mouseenter() { this.autoplay.start(); }, mouseleave() { this.autoplay.stop(); } } });
版本兼容提示
如果使用的是Swiper 3.x及更早版本,自动播放的控制方法名称不同,需替换为:
- 启动自动播放:
this.startAutoplay() - 暂停自动播放:
this.stopAutoplay()
内容的提问来源于stack exchange,提问作者leemon
相关产品推荐
相关产品推荐

