<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
ul {
min-height: 500px;
position: relative;
margin: 0 auto;
}
ul li {
float: left;
padding: 5px;
list-style: none;
}
ul li img {
width: 200px;
border: 1px solid #ccc;
border-radius: 10px;
padding: 10px;
}
</style>
<script src="./myjson.js"></script>
</head>
<body>
<ul id="myList"></ul>
<script>
let ul = document.querySelector('ul')
let tableData = JSON.parse(JSON.stringify(imglist)).slice(0, 20)
render(tableData)
// 预加载 需要一个默认图片
function render(data) {
let str = ''
data.forEach((item, index) => {
// console.log(item)
str +=
`<li><img class='img-item${index}' src='./default.jpg' /></li>`
});
ul.innerHTML = str
setTimeout(() => {
loopload(data)
})
}
// 预加载函数
function loopload(data, i = 0) {
// 获取当前这条数据
let it = data[i]
if (it) {
// 创建img标签
let img = new Image()
// 设置src 缓存
img.src = it.src
// 图片加载完成以后 缓存结束 那么就应该设置到页面当中
img.onload = () => {
document.querySelector(`.img-item${i}`).src = it.src
loopload(data, i + 1)
}
}
}
//滚动到底部加载数据关键在于获取scrollTop,scrollHeight,clientHeight,监听到底部后就数据添加或者截取总数据,然后渲染
let num = 20
window.onscroll = () => {
let nowTop = document.documentElement.scrollTop
let maxTop = document.documentElement.scrollHeight
let clientHeight = document.documentElement.clientHeight
// console.log(nowTop+clientHeight,maxTop )
if (nowTop + clientHeight >= maxTop) {
num += 10
console.log('你改加载更多数据了')
let data = imglist.slice(num - 10, num)
moreRender(data)
}
}
function moreRender(data) {
let str = ''
let num = tableData.length
data.forEach((item, index) => {
// console.log(item)
str +=
`<li><img class='img-item${tableData.length + index}' src='./default.jpg' /></li>`
});
ul.innerHTML += str
tableData = [...tableData, ...data]
setTimeout(() => {
loopload(tableData)
})
}
</script>
</body>
</html>