autoScroll.js
let timer = null //定时器
let isScrolling = true //是否滚动
export default {
bind(el, binding, vnode) {
init(el, binding, vnode)
},
update(el, binding, vnode) {
// 当绑定值更新时,停止当前滚动并重新初始化
clearTimeout(timer)
init(el, binding, vnode)
},
unbind(el) {
// 清理定时器
clearTimeout(timer)
}
}
function init(el, binding, vnode) {
// 鼠标移入时暂停滚动
el.addEventListener('mouseenter', () => {
if (options.pauseOnHover) {
isScrolling = false
timeout(el, options)
}
})
// 鼠标点击时暂停滚动
el.addEventListener('click', () => {
if (options.pauseOnHover) {
isScrolling = false
timeout(el, options)
}
})
// 触摸时暂停滚动
el.addEventListener('touchstart', () => {
if (options.pauseOnHover) {
isScrolling = false
timeout(el, options)
}
})
const options = binding.value
timer = setTimeout(() => {
startScroll(el, options)
}, 1000)
}
// 开始滚动函数
function startScroll(el, options) {
const scrollHeight = el.scrollHeight // 元素可滚动高度,包括不可见区域部分
const clientHeight = el.clientHeight // 可见区域高度
el.scrollTop += options.speed //滚动速度 1
if (el.scrollTop >= scrollHeight - clientHeight) {
clearTimeout(timer)
if (options.loop) {
// 滚动到页面底部,并且开启了循环滚动
el.scrollTop = 0
timer = setTimeout(() => {
startScroll(el, options)
isScrolling = true
}, 1000)
} else {
}
} else {
timer = setTimeout(() => {
startScroll(el, options)
}, 5)
}
}
function timeout(el, options) {
if (!isScrolling) {
clearTimeout(timer)
let second = 5
// 定时器 N 秒后执行一次 startScroll 函数
timer = setTimeout(() => {
startScroll(el, options)
isScrolling = true
}, second * 1000)
}
}
vue文件中使用
<template>
<div class="page" v-auto-scroll="scrollOptions">
<beack></beack>
<img
ref="lastItem"
class="demo"
src="path"
alt=""
/>
</div>
</template>
<script>
export default {
data() {
return {
scrollOptions: {
speed: 1, // 滚动速度(每5毫秒滚动的像素数)
pauseOnHover: true, // 鼠标移入停止滚动
loop: true // 循环滚动
}
}
}
}
</script>