class Scroll {
constructor (options = {}) {
// 滚动固定区域
this.fixedBox = options.el
// 复制的滚动区域
this.copyFixedBox = null
// 滚动的区域
this.scrollBox = null
// 滚动区域里的子元素
this.scrollChildrens = []
// 滚动的区域className
this.className = options.className || ''
// 滚动方向
this.direction = options.direction || 'top'
// 是否开启分页加载功能
this.isPage = options.isPage || false
// 是否正在处于分页加载状态,如果加载时间太长,组织下一次加载
this.isAjax = false
// 回调函数
this.callBack = options.callBack || null
// 滚动时间
this.timer = null
// 滚动速度
this.speed = options.speed || 2
// x轴移动值
this.x = 0
// y轴移动值
this.y = 0
this.methods = options.methods || null
this.init()
}
// 初始化
init () {
if (!this.fixedBox) {
console.error('请传入需要滚动的元素')
return
}
const children = this.fixedBox.childNodes
if (children[0].offsetHeight < this.fixedBox.offsetHeight) {
return false
}
this.fixedBox.style.display = 'none'
const contentParent = this.fixedBox.parentNode
const contentHTML = contentParent.innerHTML
const div = document.createElement('div')
div.innerHTML = contentHTML
const divFirstChildNode = div.childNodes[0]
contentParent.appendChild(divFirstChildNode)
this.copyFixedBox = divFirstChildNode
const fixedHtml = this.fixedBox.innerHTML
this.copyFixedBox.style.display = 'block'
this.scrollBox = document.createElement('div')
this.scrollBox.className = this.className
for (let i = 0; i < 2; i++) {
this.scrollBox.innerHTML += fixedHtml
}
this.copyFixedBox.innerHTML = ''
this.scrollChildrens = this.scrollBox.childNodes
if (this.methods) {
this.scrollChildrens.forEach(item => {
item.childNodes.forEach((child, childIndex) => {
child.onclick = () => {
this.methods(childIndex)
}
})
})
}
this.copyFixedBox.appendChild(this.scrollBox)
this.animloop()
this.copyFixedBox.onmouseenter = () => {
cancelAnimationFrame(this.timer)
}
this.copyFixedBox.onmouseleave = () => {
this.animloop()
}
this.copyFixedBox.onscroll = async () => {
if (this.copyFixedBox.scrollTop >= this.scrollChildrens[0].offsetHeight - 200) {
if (this.isPage && this.callBack && !this.isAjax) {
this.isAjax = true
this.callBack(() => {
const fixedHtml = this.fixedBox.innerHTML
this.scrollChildrens[0].innerHTML = fixedHtml
this.scrollChildrens[1].innerHTML = fixedHtml
this.isAjax = false
})
}
}
if (this.copyFixedBox.scrollTop >= this.scrollChildrens[0].offsetHeight) {
this.copyFixedBox.scrollTop = 0
}
}
}
computed () {
}
run = () => {
if (this.direction === 'top') {
this.copyFixedBox.scrollTop = this.copyFixedBox.scrollTop + this.speed
}
}
animloop = () => {
this.run()
this.timer = window.requestAnimationFrame(this.animloop)
}
}
export default Scroll
<div>
<div
ref="listBox"
class="list_box"
>
<div class="list-content">
<div
v-for="(item,index) in list"
:key="index"
class="item"
>
<p>
<span>{{ index + 1 }}</span>
<span>{{ formatData(new Date(item.date), 'YYYY年MM月DD日') || '' }}</span>
</p>
<p>{{ item.title }}</p>
</div>
</div>
</div>
</div>
<script>
import Scroll from '@/utils/Scroll'
mounted(){
new Scroll({
el: this.$refs.listBox,
speed:1,
})
}
</script>