jump(index) {
const direction = index - this.currentIndex >= 0 ? -1 : 1
const offset = Math.abs(index - this.currentIndex) * 600
const jumpSpeed = Math.abs(index - this.currentIndex) === 0 ? this.speed : Math.abs(index - this.currentIndex) * this.speed
this.move(offset, direction, jumpSpeed)
}六、自动播放与暂停
前面的写的差不多了,到这里就非常简单了,写一个函数play:
play() {
if (this.timer) {
window.clearInterval(this.timer)
this.timer = null
}
this.timer = window.setInterval(() => {
this.move(600, -1, this.speed)
}, 4000)
}除了初始化以后自动播放,还要通过mouseover和mouseleave来控制暂停与播放:
stop() {
window.clearInterval(this.timer)
this.timer = null
}七、 两处小坑
1. window.onblur 和 window.onfocus
写到这里,基本功能都差不多了。但是如果把页面切换到别的页面,导致轮播图所在页面失焦,过一段时间再切回来会发现轮播狂转。原因是页面失焦以后,setInterval停止运行,但是如果切回来就会一次性把该走的一次性走完。解决的方法也很简单,当页面失焦时停止轮播,页面聚焦时开始轮播。
window.onblur = function() { this.stop() }.bind(this)
window.onfocus = function() { this.play() }.bind(this)2. window.setInterval() 小坑
当定时器 window.setInterval() 在多个异步回调中使用时,就有可能在某种机率下开启多个执行队列, 所以为了保险起见,不仅应该在该清除时清除定时器,还要在每次使用之前也清除一遍 。
八、用props简单写两个对外接口
props: {
initialSpeed: {
type: Number,
default: 30
},
initialInterval: {
type: Number,
default: 4
}
},
data() {
......
speed: this.initialSpeed
},
computed:{
interval() {
return this.initialInterval * 1000
}
}然后再在相应的地方修改下就可以了。
完整的代码如下:
<template>
<div id="slider">
<div class="window" @mouseover="stop" @mouseleave="play">
<ul class="container" :style="containerStyle">
<li>
<img :src="sliders[sliders.length%20-%201].img" alt="">
</li>
<li v-for="(item, index) in sliders" :key="index">
<img :src="item.img" alt="">
</li>
<li>










