滑动顶部菜单栏用vue2如何实现
实现滑动顶部菜单栏的关键在于监听页面滚动事件,根据滚动位置来判断当前应该激活哪个菜单项。下面是使用Vue2实现滑动顶部菜单栏的简单示例:
- 在Vue组件中添加菜单数据和当前激活项的索引:
data() {
return {
menus: [
{ label: '菜单一', link: '#menu1' },
{ label: '菜单二', link: '#menu2' },
{ label: '菜单三', link: '#menu3' },
{ label: '菜单四', link: '#menu4' },
],
activeIndex: 0,
};
},
- 在组件的
mounted钩子函数中添加滚动事件的监听:
mounted() {
window.addEventListener('scroll', this.handleScroll);
},
- 编写
handleScroll方法,在方法中计算当前滚动位置,根据位置来判断当前应该激活哪个菜单项:
methods: {
handleScroll() {
const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
const windowHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
const menuElements = Array.from(document.querySelectorAll('.menu-item')).map(el => ({
el,
offsetTop: el.offsetTop,
offsetHeight: el.offsetHeight,
}));
let activeIndex = 0;
for (let i = 0; i < menuElements.length; i++) {
const current = menuElements[i];
const next = menuElements[i + 1];
if (scrollTop + windowHeight >= current.offsetTop + current.offsetHeight / 2) {
if (!next || scrollTop + windowHeight < next.offsetTop + next.offsetHeight / 2) {
activeIndex = i;
break;
}
}
}
this.activeIndex = activeIndex;
},
},
- 在组件的模板中渲染菜单项,并根据当前激活项的索引来添加
active类名:
<template>
<div class="menu-wrap">
<div class="menu">
<div
v-for="(menu, index) in menus"
:key="index"
:class="['menu-item', { active: activeIndex === index }]"
:href="menu.link"
>
{{ menu.label }}
</div>
</div>
</div>
</template>
<style>
.menu-wrap {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 100;
}
.menu {
display: flex;
justify-content: space-between;
background-color: #fff;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.menu-item {
display: inline-block;
padding: 12px 24px;
color: #999;
font-size: 14px;
cursor: pointer;
transition: color 0.3s ease;
}
.menu-item:hover {
color: #333;
}
.menu-item.active {
color: #333;
font-weight: bold;
border-bottom: 2px solid #333;
}
</style>
这样就可以实现一个简单的滑动顶部菜单栏了。需要注意的是,为了计算滚动位置和菜单项的位置,需要使用window.pageYOffset、document.documentElement.scrollTop和document.body.scrollTop三个属性中的一个,具体使用哪一个取决于浏览器的支持情况。同时,为了让滚动事件的监听生效,需要在组件销毁时移除事件监听,可以在beforeDestroy钩子函数中添加:
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll);
},
``
原文地址: http://www.cveoy.top/t/topic/fQZG 著作权归作者所有。请勿转载和采集!