<template>
<div>
<!-- 固定导航按钮 -->
<a-affix offset-top="10">
<a-space>
<a-button
v-for="(section, index) in sections"
:key="section.id"
:type="activeSection === section.id ? 'primary' : 'default'"
@click="scrollToSection(section.id)"
>
{{ section.name }}
</a-button>
</a-space>
</a-affix>
<!-- 滚动内容区 -->
<div ref="scrollContainer" class="content" @scroll="handleScroll">
<div v-for="(section, index) in sections" :id="section.id" :key="section.id" class="section">
<h2>{{ section.name }}</h2>
<p>{{ section.content }}</p>
</div>
</div>
</div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
// 定义滚动部分的数据
const sections = ref([
{ id: 'section1', name: 'Section 1', content: 'This is Section 1' },
{ id: 'section2', name: 'Section 2', content: 'This is Section 2' },
{ id: 'section3', name: 'Section 3', content: 'This is Section 3' },
])
// 当前激活的部分
const activeSection = ref('')
// 滚动容器引用
const scrollContainer = (ref < HTMLElement) | (null > null)
// 滚动到指定部分
const scrollToSection = (id) => {
const element = document.getElementById(id)
if (element) {
element.scrollIntoView({ behavior: 'smooth', block: 'start' })
}
}
// 滚动监听
const handleScroll = () => {
console.log('scroll', activeSection.value)
let currentSection = ''
// 遍历所有 section,判断它们是否出现在视口中
sections.value.forEach((section) => {
const element = document.getElementById(section.id)
if (element) {
const rect = element.getBoundingClientRect() //获取元素相对于视口的位置信息,返回一个 DOMRect 对象,包含 top、right、bottom、left、width 和 height 属性。
// 检查当前 section 是否进入视口中,且距离顶部足够近
if (
rect.top >= 0 &&
rect.top <= (scrollContainer.value?.clientHeight || window.innerHeight) / 2
) {
currentSection = section.id
}
}
})
// 如果当前激活部分发生变化,则更新 activeSection
if (currentSection !== activeSection.value) {
activeSection.value = currentSection
}
}
</script>
<style scoped>
.content {
margin-top: 20px;
height: 500px; /* 设置固定高度 */
overflow: auto; /* 启用滚动条 */
border: 1px solid #f0f0f0;
}
.section {
height: 500px;
padding: 20px;
border: 1px solid #f0f0f0;
margin-bottom: 10px;
}
</style>