vue实现电梯导航
实现电梯导航的基本思路
电梯导航(Anchor Navigation)是一种页面内快速跳转的交互方式,常见于长页面中。Vue实现的核心是通过scrollTo或路由哈希结合IntersectionObserver监听元素位置。
基础实现方案
HTML结构
<template>
<div class="container">
<!-- 导航锚点 -->
<div class="anchor-nav">
<a
v-for="(item, index) in anchors"
:key="index"
@click="scrollTo(item.id)"
:class="{ active: activeAnchor === item.id }"
>
{{ item.title }}
</a>
</div>
<!-- 内容区块 -->
<section
v-for="(item, index) in anchors"
:id="item.id"
:key="'content-' + index"
>
<h2>{{ item.title }}</h2>
<div>...</div>
</section>
</div>
</template>
JavaScript逻辑

export default {
data() {
return {
anchors: [
{ id: 'section1', title: '区块1' },
{ id: 'section2', title: '区块2' },
{ id: 'section3', title: '区块3' }
],
activeAnchor: ''
}
},
mounted() {
this.setupObserver();
window.addEventListener('scroll', this.handleScroll);
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll);
},
methods: {
scrollTo(id) {
const element = document.getElementById(id);
if (element) {
element.scrollIntoView({ behavior: 'smooth' });
}
},
setupObserver() {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
this.activeAnchor = entry.target.id;
}
});
}, { threshold: 0.5 });
this.anchors.forEach(item => {
const el = document.getElementById(item.id);
if (el) observer.observe(el);
});
}
}
}
优化方案:防抖与滚动阈值
methods: {
handleScroll: _.debounce(function() {
const scrollPosition = window.scrollY;
this.anchors.forEach(item => {
const el = document.getElementById(item.id);
if (el) {
const { top, bottom } = el.getBoundingClientRect();
if (top <= 100 && bottom >= 100) {
this.activeAnchor = item.id;
}
}
});
}, 100)
}
样式增强
.anchor-nav {
position: fixed;
right: 20px;
top: 50%;
transform: translateY(-50%);
}
.anchor-nav a {
display: block;
padding: 8px 12px;
color: #666;
border-left: 3px solid transparent;
}
.anchor-nav a.active {
color: #1890ff;
border-left-color: #1890ff;
}
注意事项
- 使用
IntersectionObserver需注意浏览器兼容性,必要时引入polyfill - 移动端需考虑触摸事件与滚动性能优化
- 动态内容加载时需重新计算锚点位置
- 路由模式需区分hash模式和history模式的处理方式
以上方案可根据实际需求调整滚动行为检测逻辑和交互细节。






