vue-awesome-swiper 悬停效果实现

轮播实现鼠标悬停效果,实际上就是用 mouseover、mouseleave 两个事件去实现,但是关键在于这两个事件怎么使用才能达到理想的效果。

如果直接将 mouseovermouseleave 事件绑定在 swiper 上面,就会出现一个问题: mouseovermouseleave事件被触发的次数很偶然,比如刚进入页面,鼠标放在轮播图上面会触发悬停,但轮播图自动轮播后,事件将不再触发。如果上面滑动页面,经过轮播图时,偶尔也会触发一两次,ennn。。。这并不是我想要的效果。。。。最后想了一下,大概时 loop 循环之后,事件绑定的DOM发生了偏移,导致事件偶尔触发一次。

解决办法:

<div class="box" @mouseover="enter" @mouseleave="leave">
    <swiper —— ref="mySwiper" :options="swiperOption">
        <swiper-slide v-for="(item, index) in swiper" :key="index">
            Slide{{index+1}}+
        </swiper-slide>
    </swiper>
</div>

上面说了,直接将事件绑定在 swiper 上面,因为它的不稳定性,导致事件触发只能看缘分。 所以我这里给 swiper 添加了一个父盒子,将事件绑定在父盒子上面,只要鼠标经过 class=“box” 这一区域就会触发 mouseovermouseleave 事件了。
下面我们可以通过事件去控制 swiper 的悬停效果了。

data() {
    return {
        swiperOption: {
            autoplay: {
                delay: 2000,
                disableOnInteraction: false
            },
            loop: true
        },
        swiper: [1, 2, 3, 4]
    }  
},
methods: {
    enter() {
        this.$refs.mySwiper.swiper.autoplay.stop()
    },
    leave() {
        this.$refs.mySwiper.swiper.autoplay.start()
    }
}
  • 需要注意的是,在配置 swiperOption 时,looptrue 的情况下,要在 swiper 标签上面添加 v-if=“swiper.length” ,确保 swiper 准备好之后再进行渲染,如果不添加会使一些配置信息失效。

如果我们的轮播图只有一张图,这个时候 loop 循环就有些奇怪了,看到一张图一直在转啊转。。。这里就需要简单的做一下处理,当 swiper 数组长度为 1 时,就将 swiperOption 中的 loop 只设为 false 就可以了。

data() {
    return {
        swiperOption: {
            autoplay: {
                delay: 2000,
                disableOnInteraction: false
            },
            loop: true
        },
        swiper: [1, 2, 3, 4]
    }  
},
mounted() {
    if(this.swiper.length > 1) {
        this.swiperOption.loop = true
    }else {
        this.swiperOption.loop = false
    }
},
methods: {
    enter() {
        this.$refs.mySwiper.swiper.autoplay.stop()
    },
    leave() {
        this.$refs.mySwiper.swiper.autoplay.start()
    }
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值