简单版:
核心:
元素监听scroll事件
计算可视化高度一次能装几个列表,然后从总数据中进行slice截取
每一次滚动后根据scrollTop值获取一个可以整除itemH结果进行偏移
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
list-style: none;
box-sizing: border-box;
}
li {
text-align: center;
line-height: 60px;
border-bottom: 1px solid red;
}
</style>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.13/vue.min.js"></script>
</head>
<body>
<div id="app">
<div class="box" :style="`height:${viewH}px;overflow-y:scroll;`" @scroll="handleScroll">
<ul>
<li :style="`transform:translateY(${offsetY}px); height:${itemH}px;`" v-for='i in clist' :key="i">{
{
i}}</li>
</ul>
</div>
</div>
<script>
let list = []
for (let index = 0; index < 10000; index++) {
list.push(index)
}
new Vue({
el: '#app',
data() {
return {
list,//上万条总数据
clist: [],// 页面展示数据
viewH: 500, // 外部box高度
itemH: 60, // 单项高度
scrollH: '', // 整个滚动列表高度
showNum: '',//可视化高度一次能装几个列表
offsetY: 0// 动态偏移量
}
},
mounted() {
this.scrollH = this.list.length * this.itemH;
// 计算可视化高度一次能装几个列表, 多设置几个防止滚动时候直接替换
this.showNum = Math.floor(this.viewH / this.itemH) + 4;
// 默认展示几个
this.clist = this.list.slice(0, this.showNum);
this.lastTime = new Date().getTime();
},
computed: {
// clist() { }
},
methods: {
handleScroll(e) {
if (new Date().getTime() - this.lastTime > 10) {
let scrollTop = e.target.scrollTop; // 滚去的高度
// 每一次滚动后根据scrollTop值获取一个可以整除itemH结果进行偏移
// 例如: 滚动的scrllTop = 1220 1220 % this.itemH = 20 offsetY = 1200
this.offsetY = scrollTop - (scrollTop % this.itemH);
//上面卷掉了多少,就要往下平移多少,不然showNum滚出可视区外了
console.log(scrollTop, scrollTop % this.itemH);
this.clist = this.list.slice(
Math.floor(scrollTop / this.itemH), // 计算卷入了多少条
Math.floor(scrollTop / this.itemH) + this.showNum
)
this.lastTime = new Date().getTime();
}
}
},
})
</script>
</body>
</html>
进阶版:
针对每个项的高度已知情况
滚动条展示:计算出所有项的高度,将其设置在内部背景div上,则能得出所有项都展示时,滚动条大小位置和内容一致
滑动展示列表内容的容器:
在内部背景div上,再通过放置一个容器进行定位,由上一步知道,滚动条的位置和大小与展示列表内容的容器无关,即此容器只需要管理展示的内容和自身的位置
展示的内容:通过下面步骤得出
自身的位置:通过top或transform:translate3d(0,npx,0)进行位置定位,通过scrollTop得出当前展示索引,从而计算出上屏索引,则放置的位置和上屏索引对应项的位置一致
计算能放置条数:通过列表高度和最小项的高度,计算能放置多少项
缓存与展示:分三屏进行缓存展示,应对快速滑动情况,即将三屏要展示的列表项放进数组里根据滚动位置进行刷新
上屏:当前展示索引-放置条数<0?0:上屏索引(当前展示索引-放置条数),然后从数组中根据上屏索引切出上屏的内容
中屏:要展示的内容,根据scrollTop和每一项位置进行查找(此处用了二分查找),得出当前展示的索引,然后从数组中根据当前展示的索引切出中屏的内容
下屏:当前展示的索引+放置条数>数组总条数-1?数组总条数:下屏索引(当前展示的索引+放置条数)
减少计算量:
设置一个缓存区间,如:[上屏索引+放置条数/2的位置,当前展示展示索引+放置条数/2的位置),在这个区间时,就只让列表跟随背景滑动,不计算上中下屏展示的内容以及对展示容器进行定位
对滑动事件进行防抖:window.requestAnimation进行防抖
为何根据上屏索引对应的项进行定位,能保证中屏的第一项在页面第一个起始位置:
根据滚动条展示知道,已经根据所有项的高度,进行了背景高度的填充,所以根据scrollTop得出的索引对应的项位置,就是项该在背景容器中的位置
又因为展示有上中下三屏,虽然是上中下三屏,但整个内容都是在一个div中,所以得根据中屏当前展示索引(scrollTop得出的),换算出上屏索引,再位移到上屏索引的位置
若根据中屏当前展示索引(scrollTop得出的)给div定位,则内容在滑动后,中屏的内容是在上屏的位置里
若无中上屏的缓存展示逻辑和缓存区间,只有一屏,那么会在滑动到下一项时刷新定位,虽然滑动效果一致,但会造成闪屏的现象
为何在触发列表上中下屏内容刷新以及位置重新定位时,页面展示内容位置和之前滚动的位置一致:
滑动刷新时机:不考虑缓存等,是滑到当前正在展示的第一条项高度结束,下一条项在屏幕初始位置时,才会进行定位刷新
刷新根据计算原理知道,下一条项依旧是在屏幕初始位置,所以在显示上虽然展示列表内容的容器重新进行了定位,但下一条项依旧是在屏幕初始位置,所以看起来页面展示内容位置和之前滚动的位置一致
效果图:
初始加载中屏和下屏列表项:
滑动加载上屏列表项:
滑倒列表中间等过程时,上中下屏都加载:
刷新内容,重新定位时:
刷新前:虽然定位的位置和内容变了,但是展示的内容是不变的,所以刷新能和上次滑动状态视觉效果一致
滑动到伊洛瓦底省的时候刷新:
代码示例:
源码地址
<template>
<div class="wrapper" ref="wrapper" @scroll="onScroll">
<div class="background" :style="{height:`${total_height}px`}"></div>
<div class="list" ref="container">
<div v-for="item in runList" :class="['line',getClass(item.data.type)]" :key="item" style="backgroundColor:red">
<div class="item lt">{
{
item.data.name}}</div>
<div class="item gt">{
{
item.data.value}}</div>
<div v-if="item.data.type == 3" class="img-container">
<img src="../../assets/default.png" />
</div>
</div>
</div>
</div>
</template>
<script>
import city_data from "./city.json";
export default {
props: {
cache_screens: {
// 缓冲的屏幕数量
type: Number,
default: 1
}
},
data () {
return {
list: [], // 源数据
runList: [], // 运行时的列表
total_height: 0, // 列表总高度
maxNum: 0,// 一屏幕容纳的最大数量
distance: 0 // 存储滚动的距离
}
},
mounted () {
this.genData();
this.init();
this.getRunData();
},
methods: {
getClass (type) {
switch (type) {
case 1: return "one";
case 2: return "two";
case 3: return "three";
default:
return "";
}
},
init () {
const containerHeight = parseInt(getComputedStyle(this.$refs.wrapper).height);
//一屏的最大数量
this.maxNum = Math.ceil(containerHeight / this.min_height);
console.log('max',this.maxNum)
console.log(`maxNum:${
this.maxNum}`);
},
onScroll (e) {
if (this.ticking) {
return;
}
this.ticking = true;
requestAnimationFrame(() => {
this.ticking = false;
})
const distance = e.target.scrollTop;
this.distance = distance;
this.getRunData(distance);
},
//二分法计算起始索引
getStartIndex (scrollTop) {
let start = 0, end = this.list.length - 1;
while (start < end) {
const mid = Math.floor((start + end) / 2);
const {
top, height } = this.list[mid];
if (scrollTop >= top && scrollTop < top + height) {
start = mid;
break;
} else if (scrollTop >= top + height) {
start = mid + 1;
} else if (scrollTop < top) {
end = mid - 1;
}
}
return start;
},
getRunData (distance = null) {
//滚动的总距离
const scrollTop = distance ? distance : this.$refs.container.scrollTop;
//在哪个范围内不执行滚动
if (this.scroll_scale) {
if (scrollTop > this.scroll_scale[0] && scrollTop < this.scroll_scale[1]) {
return;
}
}
console.log('gg',this.scroll_scale)
console.log(this.list)
//起始索引
let start_index = this.getStartIndex(scrollTop);
start_index = start_index < 0 ? 0 : start_index;
//上屏索引
let upper_start_index = start_index - this.maxNum * this.cache_screens;
upper_start_index = upper_start_index < 0 ? 0 : upper_start_index;
// 调整offset
this.$refs.container.style.transform = `translate3d(0,${
this.list[start_index].top}px,0)`;
//中间屏幕的元素
const mid_list = this.list.slice(start_index, start_index + this.maxNum);
// 上屏
const upper_list = this.list.slice(upper_start_index, start_index);
// 下屏元素
let down_start_index = start_index + this.maxNum;
down_start_index = down_start_index > this.list.length - 1 ? this.list.length : down_start_index;
console.log('索引',Math.floor(upper_start_index + this.maxNum / 2))
this.scroll_scale = [this.list[Math.floor(upper_start_index + this.maxNum / 2)].top, this.list[Math.ceil(start_index + this.maxNum / 2)].top];
const down_list = this.list.slice(down_start_index, down_start_index + this.maxNum * this.cache_screens);
this.runList = [...upper_list, ...mid_list, ...down_list];
},
//生成数据
genData () {
function getHeight (type) {
switch (type) {
case 1: return 50;
case 2: return 100;
case 3: return 150;
default:
return "";
}
}
let total_height = 0;
const list = city_data.map((data, index) => {
const height = getHeight(data.type);
const ob = {
index,
height,
top: total_height,
data
}
total_height += height;
return ob;
})
this.total_height = total_height; // 列表总高度
this.list = list;
this.min_height = 50; // 最小高度是50
}
}
}
</script>
<style lang="scss" scoped>
.wrapper {
position: absolute;
left: 0;
right: 0;
bottom: 0;
top: 60px;
overflow-y: scroll;
.background {
position: absolute;
top: 0;
left: 0;
right: 0;
z-index: -1;
}
.list {
position: absolute;
top: 0;
left: 0;
right: 0;
}
}
.line {
border-bottom: 1px solid #eee;
display: flex;
justify-content: space-between;
box-sizing: border-box;
.item {
height: 100%;
line-height: 40px;
color: #999;
&.lt {
margin-left: 10px;
}
&.gt {
margin-right: 10px;
}
}
&.one {
height: 50px;
}
&.two {
height: 100px;
.item {
color: #666;
}
}
&.three {
height: 150px;
.item {
color: #005aa0;
}
.img-container {
display: flex;
align-items: center;
img {
width: 100px;
height: 100px;
margin-right: 10px;
}
}
}
}
</style>