简单列表滚动 通用

  • 可以自己加一些参数 (滚动距离,是否循环加载,到底部时可以弹出一个事件进行请求等等)
  • 如果假如异步请求记得关闭定时器

/**
 * 
 * @param {传入可滚动的真实dom} dom  
 * @param {定时器延时} time 
 * @param {是否循环} loop 
 * @param {滚动距离} loop 
 */
function ScrollList(dom, time = 100, loop = true) {
    const copyDom = dom;
    let timeCo = null;
    if (!copyDom) {
        return false
    }
    // 创建定时器开始滚动元素
    function CreatedTime() {
        timeCo = setInterval(() => {
            // 元素⾃增距离顶部1像素
            copyDom.scrollTop += 1;
            // 判断元素是否滚动到底部(可视⾼度+距离顶部=整个⾼度)
            if (copyDom.clientHeight + copyDom.scrollTop == copyDom.scrollHeight) {
                // 重置table距离顶部距离
                copyDom.scrollTop = 0;
            }
        }, time);
    }
    CreatedTime()
    // 移入事件
    copyDom.addEventListener("mouseover",function(){
        clearInterval(timeCo)
    })
    // 移出事件
    copyDom.addEventListener("mouseout",function(){
        CreatedTime()
    })
}
export {
    ScrollList
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
当然可以,以下是一个简单的虚拟滚动组件的示例代码: ```vue <template> <div class="virtual-scroll" ref="scrollWrapper" @scroll="handleScroll"> <div :style="{height: totalHeight + 'px'}"></div> <div :style="{transform: 'translateY(' + offsetY + 'px)'}"> <div v-for="(item, index) in visibleList" :key="index" :style="{height: itemHeight + 'px'}">{{ item }}</div> </div> </div> </template> <script> export default { props: { list: { type: Array, required: true }, itemHeight: { type: Number, required: true }, visibleCount: { type: Number, required: true } }, data() { return { totalHeight: 0, offsetY: 0, startIndex: 0, endIndex: this.visibleCount - 1 }; }, computed: { visibleList() { return this.list.slice(this.startIndex, this.endIndex + 1); } }, mounted() { this.totalHeight = this.list.length * this.itemHeight; }, methods: { handleScroll() { const scrollTop = this.$refs.scrollWrapper.scrollTop; const startIndex = Math.floor(scrollTop / this.itemHeight); const endIndex = startIndex + this.visibleCount - 1; this.startIndex = startIndex; this.endIndex = endIndex; this.offsetY = startIndex * this.itemHeight; } } }; </script> <style scoped> .virtual-scroll { overflow: auto; position: relative; } .virtual-scroll > div:nth-child(1) { position: absolute; top: 0; left: 0; right: 0; } .virtual-scroll > div:nth-child(2) { position: absolute; top: 0; left: 0; right: 0; } </style> ``` 这个组件接受三个props: - list:要显示的数据列表 - itemHeight:每个数据项的高度 - visibleCount:可见的数据项数量 组件内部使用了一个滚动容器,容器中包含两个div,第一个div的高度等于所有数据项的高度之和,第二个div包含了所有可见的数据项,通过计算滚动容器的scrollTop和startIndex,可以确定当前应该显示哪些数据项。同时,为了避免在滚动时频繁更新DOM,我们使用了translateY来实现滚动效果,而不是设置每个数据项的top值。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值