因需要实现一个动态的吸顶组件,吸顶之后的目标对象根据滚动条的滚动位置动态增加,效果如下:

组件代码如下:
export default {
created () {
if (!this.handleScroll_mixin) {
throw new Error("【scrollWebviewMixin】handleScroll_mixin 方法未定义")
}
window.addEventListener("scroll", this.handleScroll_mixin,true)
},
beforeDestroy () {
window.removeEventListener("scroll", this.handleScroll_mixin,true)
},
}
<template>
<div class="stickyBox" :style="{'display':headerFixed?'block':'none'}">
<slot name="recodes"></slot>
</div>
</template>
<script>
import scrollMixin from "./scrollMixin.js"
export default {
mixins: [scrollMixin],
name: "StickyBox",
props:{
stickyList:{
type: Array,
default:()=>[]
},
listenScrollId: String
},
data() {
return {
staticList:[],
headerFixed: 0
}
},
methods: {
handleScroll_mixin() {
if(!this.staticList.length){
this.stickyList.map(item=>{
const $el = document.querySelector(`[stickyid="${item}"]`)
this.staticList.push({offsetTop: $el?.offsetTop+$el?.offsetHeight, id: item})
if(document.querySelector(`[stickyid-link="${item}"]`)){
document.querySelector(`[stickyid-link="${item}"]`).style.display="none"
}
})
}
const scrollTop = document.querySelector(this.listenScrollId)?.scrollTop || 0
this.headerFixed = scrollTop > 0
this.staticList.map(item=>{
const element = document.querySelector(`[stickyid-link="${item.id}"]`)
if(scrollTop >=item.offsetTop){
if(element && element.style.display === "none")
element.style.display="block"
}else{
if(element && element.style.display === "block")
element.style.display="none"
}
})
}
}
}
</script>
<style>
.stickyBox {
width: 100%;
position: sticky;
top: 0px;
left: 0px;
right: 0px;
z-index: 100;
background-color: #fff;
}
.stickyBox::after {
content: "";
position: absolute;
top: 100%;
left: 0;
right: 0;
height: 16px;
background: linear-gradient(
180deg,
rgba(0, 0, 0, 0.05) 0%,
rgba(0, 0, 0, 0) 100%
);
}
</style>
使用
<template>
<div id="StickyBoxScroll-inClass">
<!-- 引用 -->
<StickyBox :stickyList="stickyList" :listenScrollId="'#StickyBoxScroll-inClass'" >
<template v-slot:recodes>
<!--要吸顶的内容 -->
<div :stickyid-link='2'>
<div>想要吸顶的组件1</div>
</div>
<div :stickyid-link='1'>
<div >想要吸顶的组件2</div>
</div>
</template>
</StickyBox>
<!--被滚动监听的元素或组件,当滚动条超过次此目标元素的位置时,上面stickyid-link对应stickyid的吸顶展示元素就会出现 -->
<div :stickyid='1'></div>
<div :stickyid='2'></div>
</div>
</template>
<script>
export default {
data() {
return{
stickyList:["1","2"]
}
}
</script>