封装吸顶组件
<template>
<div>
<div class="ceilingBox" :class="{ fixed: isFixed }" :style="ceilingStyle">
<slot></slot>
</div>
</div>
</template>
<script>
export default {
name: "CeilingBox",
props: {
type: {},
ceilingStyle: {},
// 距离顶部多少像素开始吸顶
heightFromTop:{
default: () => 70
}
},
data() {
return {
isFixed: false,
};
},
mounted() {
window.addEventListener("scroll", this.handleScroll);
},
destroyed() {
window.removeEventListener("scroll", this.handleScroll);
},
methods: {
handleScroll() {
const top = this.$el.getBoundingClientRect().top;
if (top <= heightFromTop) {
this.isFixed = true;
} else {
this.isFixed = false;
}
},
},
};
</script>
<style scoped>
.fixed {
/* width: calc(100vw - 280px) !important; */
width: 100%;
position: fixed;
top: 110px;
z-index: 999;
background: #fff;
box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.1);
}
</style>
然后引入组件中间包着得内容就可以吸顶了