<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<style>
.list-container {
overflow: auto;
border: 1px solid black;
height: 500px;
}
</style>
<body>
<!-- 外部容器用來固定列表容器的高度惰许,同時生成滾動條 -->
<div class="list-container">
<!-- 內(nèi)部容器用來裝元素,高度是所有元素高度的和 -->
<div class="list-container-inner"></div>
</div>
<script>
/** --------- 一些基本變量 -------- */
const itemHeight = 60;
const height = 500;
/** --------- 生成數(shù)據(jù) -------- */
const getRandomHeight = () => {
// 返回 [60, 150] 之間的隨機數(shù)
return Math.floor(Math.random() * (150 - itemHeight + 1) + itemHeight);
};
const initData = () => {
const data = [];
for (let i = 0; i < 15; i++) {
data.push({
content: `內(nèi)容:${i}`,
height: getRandomHeight(),
color: i % 2 ? 'red' : 'yellow',
});
}
return data;
};
const data = initData();
console.log('data:', data);
const cacheHeightMap = {};
const outerContainer = document.querySelector('.list-container');
const scrollCallback = () => {
let contentHeight = 0;
let paddingTop = 0;
let upperHeight = 0;
let startIndex;
let endIndex;
const innerContainer = document.querySelector('.list-container-inner');
const scrollTop = Math.max(outerContainer.scrollTop, 0);
// 遍歷所有的元素扮休,獲取當(dāng)前元素的高度褐奴、列表總高度片拍、startIndex谬哀、endIndex
for (let i = 0; i < data.length; i++) {
// 初始化的時候因為元素還沒有渲染悦屏,無法獲取元素的高度
// 所以用元素的最小高度itemHeight來進行計算黍析,保證渲染的元素個數(shù)能占滿列表
const cacheHeight = cacheHeightMap[i];
const usedHeight =
cacheHeight === undefined ? itemHeight : cacheHeight;
contentHeight += usedHeight;
if (contentHeight >= scrollTop && startIndex === undefined) {
startIndex = i;
paddingTop = contentHeight - usedHeight;
}
if (contentHeight > scrollTop + height && endIndex === undefined) {
endIndex = i;
upperHeight = contentHeight;
}
}
// 應(yīng)對列表所有元素沒有占滿整個容器的情況
if (endIndex === undefined) {
endIndex = data.length - 1;
upperHeight = contentHeight;
}
// 未渲染的元素的高度由padding-top和padding-bottom代替卖怜,保證滾動條位置正確
// 這里如果把設(shè)置pading的操作放在渲染元素之后,部分瀏覽器滾動到最后一個元素時會有問題
const paddingBottom = contentHeight - upperHeight;
innerContainer.setAttribute(
'style',
`padding-top: ${paddingTop}px; padding-bottom: ${paddingBottom}px`
);
// 從data取出要渲染的元素并渲染到容器中
const viewData = data.slice(startIndex, endIndex + 1);
innerContainer.innerHTML = '';
const fragment = document.createDocumentFragment();
for (let i = 0; i < viewData.length; i++) {
const item = document.createElement('div');
const itemData = viewData[i];
item.innerHTML = itemData.content;
item.setAttribute(
'style',
`height: ${itemData.height}px; background: ${itemData.color}`
);
fragment.appendChild(item);
}
innerContainer.appendChild(fragment);
// 存儲已經(jīng)渲染出來的元素的高度阐枣,供后面使用
const children = innerContainer.children;
let flag = startIndex;
for (const child of children) {
cacheHeightMap[flag] = child.offsetHeight;
flag++;
}
};
// 首屏渲染
scrollCallback();
// 監(jiān)聽外部容器的滾動事件
outerContainer.addEventListener('scroll', scrollCallback);
</script>
</body>
</html>
虛擬列表
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
- 文/潘曉璐 我一進店門揖赴,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人抑胎,你說我怎么就攤上這事燥滑。” “怎么了圆恤?”我有些...
- 文/不壞的土叔 我叫張陵突倍,是天一觀的道長腔稀。 經(jīng)常有香客問我,道長羽历,這世上最難降的妖魔是什么焊虏? 我笑而不...
- 正文 為了忘掉前任,我火速辦了婚禮秕磷,結(jié)果婚禮上诵闭,老公的妹妹穿的比我還像新娘。我一直安慰自己澎嚣,他們只是感情好疏尿,可當(dāng)我...
- 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著易桃,像睡著了一般褥琐。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上晤郑,一...
- 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼签赃!你這毒婦竟也來了谷异?” 一聲冷哼從身側(cè)響起,我...
- 正文 年R本政府宣布迹淌,位于F島的核電站河绽,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏唉窃。R本人自食惡果不足惜耙饰,卻給世界環(huán)境...
- 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望纹份。 院中可真熱鬧苟跪,春花似錦、人聲如沸蔓涧。這莊子的主人今日做“春日...
- 文/蒼蘭香墨 我抬頭看了看天上的太陽元暴。三九已至篷扩,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間茉盏,已是汗流浹背瞻惋。 一陣腳步聲響...
推薦閱讀更多精彩內(nèi)容
- 前言 場景是小程序長列表優(yōu)化添瓷,框架基于mpvue,固定高度值纱。(動態(tài)高度暫時先不考慮) 關(guān)于recycle-view...
- 導(dǎo)讀 本文適用于以下三種讀者 只想要了解一下虛擬列表可閱讀“實現(xiàn)一個簡單的虛擬列表”之前的部分 想初步探究虛擬列表...
- 理論 當(dāng)我們有大量數(shù)據(jù)需要渲染時咱筛,會照成頁面的卡頓,這是由于頁面的dom太多照成的杆故,我我們可以使用虛擬列表來優(yōu)化顯...