计算列表高度区间,ul里的li
- 定义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)
}
}
- 数据监听,改变时计算
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)`
}
})