vue实现滚动监听到锚点
时间: 2023-09-08 17:10:31 浏览: 50
在 Vue 中实现滚动监听到锚点,可以通过以下步骤:
1. 在需要监听滚动的容器上,绑定 `@scroll` 事件。
2. 通过 `getBoundingClientRect()` 方法获取每个锚点元素的位置信息,得到它们距离容器顶部的距离。
3. 在滚动事件处理函数中,获取当前容器滚动的距离,并与每个锚点元素的位置信息进行比较,判断当前容器滚动到了哪个锚点的位置。
4. 将滚动到的锚点信息保存在 Vue 实例的数据中,并在模板中根据该数据展示对应的内容。
以下是一个简单的示例代码:
```vue
<template>
<div class="scroll-container" @scroll="handleScroll">
<div class="section" v-for="(section, index) in sections" :key="index">
<h2>{{ section.title }}</h2>
<p>{{ section.content }}</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
activeSection: 0, // 默认选中第一个锚点
sections: [
{ title: "Section 1", content: "Content 1" },
{ title: "Section 2", content: "Content 2" },
{ title: "Section 3", content: "Content 3" },
{ title: "Section 4", content: "Content 4" },
],
};
},
mounted() {
this.calculatePositions();
},
methods: {
calculatePositions() {
// 获取每个锚点元素的位置信息
this.positions = this.sections.map((section) => {
const element = document.getElementById(section.title);
return {
title: section.title,
top: element.getBoundingClientRect().top + this.$refs.container.scrollTop,
};
});
},
handleScroll() {
const scrollTop = this.$refs.container.scrollTop;
// 判断当前滚动到了哪个锚点
for (let i = 0; i < this.positions.length; i++) {
const position = this.positions[i];
if (scrollTop >= position.top && scrollTop < position.top + 400) {
this.activeSection = i;
break;
}
}
},
},
};
</script>
```
在该示例中,使用 `getBoundingClientRect()` 方法获取每个锚点元素的位置信息,并保存在 `positions` 数组中。在滚动事件处理函数中,获取当前容器滚动的距离,并与每个锚点元素的位置信息进行比较,判断当前容器滚动到了哪个锚点的位置。最后将滚动到的锚点信息保存在 `activeSection` 中,用于在模板中展示对应的内容。