【自制破轮子】requestAnimationFrame简单自动滚屏

429 阅读1分钟

这边的一个jquery项目,需要弄一个自动滚屏,懒得找插件,就用已知的知识,手写了一个。 顺手又改了一个纯js版本的

纯JS版本

应该也在vue版本上直接用的,直接new出来就行了,或者把this.animate()给提取出来,可以手动控制 this.domBind()可以不用,通过this.animate()和this.flag的控制就可以主动切换。 不过如果配合vue的话,这些都可以作为参数将控制权抛出去,反正行数不多,随便怎么改都行 后期最好加上当页面切换或者窗口最小化时,停止动画的事件绑定

class ScrollDiv {
    constructor(el, frame = 1) {
        this.el = el
        this.frame = frame

        // 外部最大高度
        this.maxHeight = this.el.clientHeight
        this.realHeight = this.el.scrollHeight

        // 两个高度差值
        this.scrollHeight = this.realHeight - this.maxHeight

        // 当前高度
        this.nowHeight = this.el.scrollTop

        this.flag = true
        this.domBind()
        this.animate()
    }

    // 执行变化
    move() {
        this.el.scrollTop = this.nowHeight
    }

    // 动画执行
    animate() {
        if (this.nowHeight >= this.scrollHeight) {
            this.el.scrollTop = 0
            this.nowHeight = 0
        }

        this.nowHeight += this.frame
        window.requestAnimationFrame(() => {
            if (this.flag) {
                this.move()
                this.animate()
            }
        })
    }

    // 绑定鼠标事件
    domBind() {
        this.el.addEventListener("mouseenter", () => {
            this.flag = false
        })
        this.el.addEventListener("mouseleave", () => {
            this.flag = true
            this.nowHeight = this.el.scrollTop
            this.animate()
        })
    }

}

jquery版本

实测可用(只能有一个子节点,不过也可以照着上面的改),破是破了点,不过跟业务强绑定,就这样吧

const tableScroll = new ScrollDiv(document.querySelector("index-table"), 1)
tableScroll.animate()

class ScrollDiv {
    constructor(el, frame = 1) {
        this.el = el
        this.frame = frame
        this.$el = $(el)
        this.$child = this.$el.children()

        // 外部最大高度
        this.maxHeight = this.$el.innerHeight()
        // 子元素最大高度
        this.realHeight = this.$child.height()

        // 两个高度差值
        this.scrollHeight = this.realHeight - this.maxHeight

        // 当前高度
        this.nowHeight = this.$el.scrollTop()

        this.flag = true
        this.domBind()
    }

    // 开始动画
    move() {
        this.$el.scrollTop(this.nowHeight)
    }

    animate() {
        if (this.nowHeight >= this.scrollHeight) {
            this.$el.scrollTop(0)
            this.nowHeight = 0
        }

        this.nowHeight += this.frame
        window.requestAnimationFrame(() => {
            if (this.flag) {
                this.move()
                this.animate()
            }
        })
    }

    domBind() {
        this.$el.on("mouseenter", () => {
            this.flag = false
        })
        this.$el.on("mouseleave", () => {
            this.flag = true
            this.nowHeight = this.$el.scrollTop()
            this.animate()
        })
    }

}