用v-for遍历出来的导航栏怎么实现页面滑动到哪块导航栏那块高亮
要实现页面滑动到哪块导航栏那块高亮,可以结合使用v-for和scroll事件来实现。
首先,在导航栏的HTML代码中,使用v-for指令遍历导航栏的项目,并给每个项目绑定一个唯一的标识符,例如id属性。
<div id="app">
<nav>
<ul>
<li v-for="item in items" :key="item.id" :id="item.id" @click="scrollToSection(item.id)">
{{ item.title }}
</li>
</ul>
</nav>
<div class="sections">
<div id="section1" class="section">Section 1</div>
<div id="section2" class="section">Section 2</div>
<div id="section3" class="section">Section 3</div>
<div id="section4" class="section">Section 4</div>
</div>
</div>
然后,在Vue实例中,定义导航栏的项目数组,并添加一个scrollToSection方法,用于处理点击导航栏项目时的滚动事件。
new Vue({
el: "#app",
data: {
items: [
{ id: "section1", title: "Section 1" },
{ id: "section2", title: "Section 2" },
{ id: "section3", title: "Section 3" },
{ id: "section4", title: "Section 4" }
]
},
methods: {
scrollToSection(id) {
const element = document.getElementById(id);
element.scrollIntoView({ behavior: "smooth" });
}
}
});
最后,在CSS中添加一个样式类,用于高亮当前导航栏项目。
li.active {
font-weight: bold;
}
接下来,我们需要监听页面的滚动事件,并根据滚动位置来判断当前应该高亮的导航栏项目。可以使用window对象的scroll事件来监听滚动事件。
new Vue({
// ...
mounted() {
window.addEventListener("scroll", this.handleScroll);
},
methods: {
// ...
handleScroll() {
const sections = document.getElementsByClassName("section");
const navItems = document.querySelectorAll("nav li");
for (let i = 0; i < sections.length; i++) {
const section = sections[i];
const navItem = navItems[i];
const rect = section.getBoundingClientRect();
if (rect.top >= 0 && rect.bottom <= window.innerHeight) {
navItem.classList.add("active");
} else {
navItem.classList.remove("active");
}
}
}
}
});
以上代码会通过遍历每个section元素,使用getBoundingClientRect方法获取每个section元素的位置信息,如果当前section元素在可视区域内,则给对应的导航栏项目添加active类,否则移除active类。
最后,记得在Vue实例的beforeDestroy钩子中移除scroll事件监听。
new Vue({
// ...
beforeDestroy() {
window.removeEventListener("scroll", this.handleScroll);
},
// ...
});
这样,当页面滚动到相应的section时,对应的导航栏项目就会高亮显示
原文地址: http://www.cveoy.top/t/topic/iDMh 著作权归作者所有。请勿转载和采集!