vue2项目只需要改变样式就可实现
<div class="filter-criteria" class="isfixed" :class="{ 'isfixed' : isFixed }">
</div>
// 如果发现vue2不加滚动事件实现不了,再把这段js加上
data() {
return {
isFixed: false,
scrollTop: 0,
barOffsetTop: 0,
}
},
mounted() {
this.$nextTick(() => {
const element = document.getElementsByClassName('filter-criteria')[0]
if(element) {
this.barOffsetTop += element.offsetTop
}
})
},
methods: {
handleScroll(e) {
this.scrollTop = e.target.scrollTop
const top = window.pageYOffset || e.target.scrollTop
if(top >= this.barOffsetTop) {
this.isFixed = true
}else {
this.isFixed = false
}
},
}
<style>
.isfixed {
position: sticky;
left: 0px;
top: 0;
bottom: auto;
z-index: 999;
box-shadow: 0 0 10px rgba(107,107,107, 20%) !important;
width: auto !important;
}
</style>
vue3项目需要监听滚动事件,滚动到顶部时添加'isfixed',没有滚动到顶部时去掉'isfixed'
// 在带有滚动条的div上绑定滚动事件
<div @scroll="handleScroll">
<div class="filter-criteria">
</div>
</div>
const barOffsetTop = ref(0)
const scrollTop = ref(0)
onActivated(() => {
nextTick(() => {
barOffsetTop.value += document.getElementsByClassName('filter-criteria')[0]?.offsetTop
})
})
const handleScroll = (e: any) => {
scrollTop.value = e.target.scrollTop
const top = window.pageYOffset || e.target.scrollTop
if(top >= barOffsetTop.value) {
document.getElementsByClassName('filter-criteria')[0].classList.add('isfixed')
}else {
document.getElementsByClassName('filter-criteria')[0].classList.remove('isfixed')
}
}
<style>
.isfixed {
position: sticky;
left: 0px;
top: 0;
bottom: auto;
z-index: 999;
box-shadow: 0 0 10px rgba(107,107,107, 20%) !important;
width: auto !important;
}
</style>