如何在鼠标悬停时立即停止Swiper自动播放(中断过渡)
Vue中让自动播放的Swiper鼠标悬停立即停在当前位置
直接给你可行的实现方案,亲测有效:
步骤1:绑定Swiper实例与事件
先在模板里给Swiper加ref,同时绑定鼠标悬停/离开事件:
<template> <swiper ref="mySwiper" :autoplay="{ delay: 2000, disableOnInteraction: false }" :speed="600" @mouseenter="stopSwiperImmediately" @mouseleave="resumeSwiper" > <swiper-slide>轮播项1</swiper-slide> <swiper-slide>轮播项2</swiper-slide> <swiper-slide>轮播项3</swiper-slide> </swiper> </template>
注意disableOnInteraction: false必须加,不然手动停止后自动播放不会恢复。
步骤2:编写悬停中断逻辑
在组件方法里,直接操作Swiper实例和DOM,强制终止动画:
export default { methods: { stopSwiperImmediately() { const swiper = this.$refs.mySwiper.swiper; // 先停掉自动播放 swiper.autoplay.stop(); // 获取轮播的wrapper容器 const wrapper = swiper.wrapperEl; // 拿到当前实时的位置(transform值) const currentPos = window.getComputedStyle(wrapper).transform; // 清除过渡动画,把位置固定死 wrapper.style.transition = 'none'; wrapper.style.transform = currentPos; // 强制浏览器重绘,避免动画残留 void wrapper.offsetWidth; }, resumeSwiper() { const swiper = this.$refs.mySwiper.swiper; // 恢复过渡动画 swiper.wrapperEl.style.transition = ''; // 重启自动播放 swiper.autoplay.start(); } } }
针对高版本Swiper的简化写法
如果你用的是Swiper 8及以上版本,不用操作DOM,直接调用API就能搞定:
stopSwiperImmediately() { const swiper = this.$refs.mySwiper.swiper; swiper.autoplay.stop(); // 用0毫秒的滑动时长,直接跳转到当前激活的slide,瞬间终止动画 swiper.slideTo(swiper.activeIndex, 0); }
原理很简单:要么直接把当前动画的实时位置固定,要么用Swiper自带的瞬间跳转API,两种方法都能实现悬停时立即中断过渡的效果。
内容的提问来源于stack exchange,提问作者whatislove codeis
相关产品推荐
相关产品推荐

