vue实现吸顶
Vue 实现吸顶效果的方法
吸顶效果指的是当页面滚动到某个元素时,该元素固定在顶部不动。以下是几种常见的实现方式:
使用 CSS 的 position: sticky
最简单的方法是使用 CSS 的 position: sticky 属性,无需 JavaScript。

<template>
<div class="sticky-header">
吸顶内容
</div>
</template>
<style>
.sticky-header {
position: sticky;
top: 0;
z-index: 100;
background: white;
}
</style>
position: sticky 需要指定 top 值,表示距离顶部多少像素时开始固定。兼容性较好,但旧版本浏览器可能需要前缀。
监听滚动事件动态添加类名
如果需要更复杂的逻辑或兼容旧浏览器,可以通过监听滚动事件动态添加类名。

<template>
<div :class="{'sticky': isSticky}" ref="header">
吸顶内容
</div>
</template>
<script>
export default {
data() {
return {
isSticky: false
}
},
mounted() {
window.addEventListener('scroll', this.handleScroll)
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll)
},
methods: {
handleScroll() {
const headerOffset = this.$refs.header.offsetTop
this.isSticky = window.pageYOffset > headerOffset
}
}
}
</script>
<style>
.sticky {
position: fixed;
top: 0;
width: 100%;
z-index: 100;
background: white;
}
</style>
使用 Intersection Observer API
现代浏览器支持 Intersection Observer API,性能比滚动事件更好。
<template>
<div :class="{'sticky': isSticky}" ref="header">
吸顶内容
</div>
<div ref="observerTarget"></div>
</template>
<script>
export default {
data() {
return {
isSticky: false
}
},
mounted() {
const observer = new IntersectionObserver((entries) => {
this.isSticky = !entries[0].isIntersecting
}, {threshold: [1]})
observer.observe(this.$refs.observerTarget)
}
}
</script>
使用第三方库
如果需要更复杂的功能,可以考虑使用第三方库如 vue-sticky-directive 或 vue-use 中的 useScroll。
<template>
<div v-sticky>
吸顶内容
</div>
</template>
<script>
import { directive as sticky } from 'vue-sticky-directive'
export default {
directives: {
sticky
}
}
</script>
每种方法各有优缺点,position: sticky 最简单但功能有限,滚动事件兼容性好但性能稍差,Intersection Observer 性能最好但兼容性稍弱。根据项目需求选择合适的方法。






