列表title依次懸浮並將上一個title頂到頂部至消失,仿微信通訊錄列表效果和支付寶賬單頁列表效果,初步實現,若有不足請多指教
<template>
<div>
<div class="subTile"></div>
<div v-for="(item,index) in lists" :key="index" >
<div class="pre" :class="{'prelist':item.isFixed}">
{{item.title}}
</div>
<div ref="list" class="title" :class="{'isListFixed':item.isFixed}">
{{item.title}}
</div>
<div class="list" v-for="i in item.checks" :key="i"></div>
</div>
</div>
</template>
<script>
export default {
data () {
return {
barFixed:false,
lists : [
{title:'一月份',
checks:10,
isFixed:false,
isUp:false
},
{title:'二月份',
checks:20,
isFixed:false,
isUp:false
},
{title:'三月份',
checks:50,
isFixed:false,
isUp:false
}
]
}
},
methods: {
handleScroll(l,index){
let top = l.offsetTop;
if(index == this.$refs.list.length - 1){
window.addEventListener('scroll',()=>{
let scrollTop= document.documentElement.scrollTop || document.body.scrollTop
if(scrollTop >=top){
this.lists[index].isFixed = true;
l.style.top = 0 + 'px';
}else{
this.lists[index].isFixed = false;
}
})
}else{
let nextTop;
if(this.$refs.list[index+1]){
nextTop = this.$refs.list[index+1].offsetTop;
}
window.addEventListener('scroll',()=>{
let scrollTop= document.documentElement.scrollTop || document.body.scrollTop
if(scrollTop >=top && scrollTop <=nextTop){
let differ = nextTop - scrollTop
this.lists[index].isFixed = true;
if(0 <=differ && differ<= 40){
l.style.top = (differ - 40) + 'px';
}else{
l.style.top = 0 + 'px';
}
}else{
this.lists[index].isFixed = false;
}
})
}
},
},
created () {},
mounted () {
this.$nextTick(function(){
this.$refs.list.forEach((l,index)=>{
this.handleScroll(l,index)
})
})
}
}
</script>
<style lang="less" scoped>
.pre{
height: 40px;
visibility: hidden;
display: none;
}
.prelist{
display: block;
}
.subTile{
height: 20px;
background: green;
}
.isFixed{
position: fixed;
// top:0;
left: 0;
z-index: 10;
width: 100%;
}
.isListFixed{
position: fixed;
top:0;
left: 0;
z-index: 10;
width: 100%;
}
.title{
height: 40px;
background: #ccc;
}
.list{
height: 30px;
background: lightblue
}
.list:nth-child(odd){
background: lightcoral
}
</style>
複製程式碼