vue实现吸顶header
Vue 实现吸顶 Header
使用 CSS position: sticky 实现
在 Vue 中,最简单的吸顶效果可以通过 CSS 的 position: sticky 属性实现。这种方法不需要额外的 JavaScript 代码,性能较好。
<template>
<div class="header" :class="{ 'sticky': isSticky }">
<!-- Header 内容 -->
</div>
</template>
<style>
.header {
height: 60px;
background: #fff;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.sticky {
position: sticky;
top: 0;
z-index: 100;
}
</style>
使用 Vue 监听滚动事件
如果需要更复杂的控制逻辑,可以通过监听滚动事件动态添加样式。
<template>
<div class="header" :class="{ 'sticky': isSticky }">
<!-- Header 内容 -->
</div>
</template>
<script>
export default {
data() {
return {
isSticky: false
}
},
mounted() {
window.addEventListener('scroll', this.handleScroll)
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll)
},
methods: {
handleScroll() {
this.isSticky = window.scrollY > 0
}
}
}
</script>
<style>
.header {
height: 60px;
background: #fff;
transition: all 0.3s ease;
}
.sticky {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 100;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
</style>
使用 Intersection Observer API
对于更现代的解决方案,可以使用 Intersection Observer API 来检测元素是否进入视口。
<template>
<div>
<div ref="sentinel" style="height: 1px;"></div>
<div class="header" :class="{ 'sticky': isSticky }">
<!-- Header 内容 -->
</div>
</div>
</template>
<script>
export default {
data() {
return {
isSticky: false,
observer: null
}
},
mounted() {
this.observer = new IntersectionObserver(([entry]) => {
this.isSticky = !entry.isIntersecting
}, { threshold: [1] })
this.observer.observe(this.$refs.sentinel)
},
beforeDestroy() {
this.observer.disconnect()
}
}
</script>
<style>
/* 同上 */
</style>
注意事项
- 使用
position: sticky时,确保父容器没有设置overflow: hidden,否则会失效。 - 固定定位的 Header 可能会遮挡下方内容,需要为页面主体添加相应的 padding-top。
- 在移动端,可能需要考虑性能优化,避免频繁触发滚动事件。
- 对于复杂的吸顶效果(如动态高度变化),可能需要结合 CSS 动画和 JavaScript 控制。







