vue实现楼梯效果
Vue 实现楼梯效果
楼梯效果通常指页面滚动时,侧边栏或导航栏跟随滚动并高亮当前所在区域的功能。以下是实现方法:
使用 Vue 和滚动监听
安装依赖(如需要):
npm install vue-router
在 Vue 组件中实现基本结构:
<template>
<div class="container">
<div class="content" ref="content">
<section v-for="(item, index) in sections" :id="'section-' + index" :key="index">
<h2>{{ item.title }}</h2>
<p>{{ item.content }}</p>
</section>
</div>
<div class="stair-nav">
<ul>
<li
v-for="(item, index) in sections"
:key="index"
:class="{ active: currentSection === index }"
@click="scrollTo(index)"
>
{{ item.title }}
</li>
</ul>
</div>
</div>
</template>
添加样式:
.container {
display: flex;
}
.content {
flex: 1;
height: 2000px;
}
.stair-nav {
width: 200px;
position: fixed;
right: 20px;
top: 50%;
transform: translateY(-50%);
}
.stair-nav li {
padding: 10px;
cursor: pointer;
}
.stair-nav li.active {
color: red;
font-weight: bold;
}
section {
height: 500px;
margin-bottom: 20px;
}
JavaScript 部分:
<script>
export default {
data() {
return {
sections: [
{ title: 'Section 1', content: 'Content 1' },
{ title: 'Section 2', content: 'Content 2' },
{ title: 'Section 3', content: 'Content 3' }
],
currentSection: 0
}
},
mounted() {
window.addEventListener('scroll', this.handleScroll)
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll)
},
methods: {
handleScroll() {
const scrollPosition = window.scrollY
this.sections.forEach((section, index) => {
const element = document.getElementById(`section-${index}`)
if (element) {
const offsetTop = element.offsetTop
const offsetHeight = element.offsetHeight
if (scrollPosition >= offsetTop && scrollPosition < offsetTop + offsetHeight) {
this.currentSection = index
}
}
})
},
scrollTo(index) {
const element = document.getElementById(`section-${index}`)
if (element) {
window.scrollTo({
top: element.offsetTop,
behavior: 'smooth'
})
}
}
}
}
</script>
使用第三方库
对于更复杂的需求,可以考虑使用第三方库如 vue-scrollto:
安装:
npm install vue-scrollto
使用示例:
import VueScrollTo from 'vue-scrollto'
Vue.use(VueScrollTo)
// 在方法中调用
this.$scrollTo(`#section-${index}`, 500, { easing: 'ease-in-out' })
注意事项
- 性能优化:滚动事件会频繁触发,建议添加防抖处理
- 响应式设计:在小屏幕设备上可能需要隐藏楼梯导航或改变其位置
- 无障碍访问:确保导航项有适当的 ARIA 属性
以上方法提供了基本的楼梯效果实现,可以根据实际需求进行调整和扩展。







