<template>
<div>
<ul class="directory">
<li v-for="item in directory" :key="item.id" @click="scrollToSection(item.id)">
{{ item.title }}
</li>
</ul>
<div ref="pageContent" class="page-content">
<div v-for="section in directory" :key="section.id" :id="section.id" class="section">
<h2>{{ section.title }}</h2>
</div>
</div>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
const pageContent = ref(null);
const directory = [
{ id: 'section1', title: '标题 1' },
{ id: 'section2', title: '标题 2' },
{ id: 'section3', title: '标题 3' },
// ... 其他目录项
];
const scrollToSection = (sectionId) => {
console.log(sectionId);
const targetSection = pageContent.value.querySelector(`#${sectionId}`);//"这个id不能时数字"
console.log(targetSection);
if (targetSection) {
targetSection.scrollIntoView({ behavior: 'smooth' });
}
};
</script>
<style>
.directory {
list-style: none;
padding: 0;
}
.directory li {
cursor: pointer;
margin-bottom: 5px;
}
.page-content {
padding: 20px;
}
.section {
margin-bottom: 40px;
height: 1000px;
background-color: pink;
}
</style>
点击标题2
注意!!!!整体内容高度不够时无法滚动