歌手列表固定标题实现

该代码段展示了如何在JavaScript中计算
    列表中
  • 元素的高度并存储在数组中。通过数据监听实现实时更新,自定义事件用于触发滚动回调函数,获取滚动位置。当滚动到特定高度区间时,确定当前选中的列表索引和距离顶部的距离,用于动态调整元素的偏移量。
摘要由CSDN通过智能技术生成

计算列表高度区间,ul里的li

  1. 定义listHeights数组存放,初始化清空,遍历累加,
function calculate() {
        const list = groupRef.value.children
        const listHeightsVal = listHeights.value
        let height = 0

        listHeightsVal.length = 0
        listHeightsVal.push(height)

        for(let i = 0; i < list.length; i++) {
            height += list[i].clientHeight
            listHeightsVal.push(height)
        }
    }

  1. 数据监听,改变时计算
 watch(() => props.data,async () => {
        await nextTick()
        calculate()
    })

3.自定义事件emit

:probe-type="3"实时派发

回调函数onscroll 纵向滚动值

function onScroll(pos) {
        scrollY.value = -pos.y
    }

4.监听滚动到哪个区间内,获取索引和标题
distance是区间到顶部的距离

watch(scrollY, (newY) => {
        const listHeightsVal = listHeights.value
        for(let i = 0; i < listHeightsVal.length - 1; i++) {
            const heightTop = listHeightsVal[i]
            const heightBottom = listHeightsVal[i + 1]
            if(newY >= heightTop && newY <= heightBottom) {
                currentIndex.value = i
                distance.value = heightBottom - newY
            }
        }
    })

5.偏移量

const fixedStyle = computed(() => {
        const distanceVal = distance.value
        const diff = (distanceVal > 0 && distanceVal < TITLE_HEIGHT) ? distanceVal - TITLE_HEIGHT : 0
        return {
            transform: `translate3d(0,${diff}px,0)`
        }
    })

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值