在移动端长列表,需要通过上拉加载提升性能
主要目的是为了提升性能
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="list">
</div>
<script>
const list=document.getElementById('list')
let page=1
function loadMoreData(page){
return fetch(`https://example.com/api/data?page=${page}`)
.then(response =>response.json())
.then(data=>{
data.items.forEach(item=>{
const div=document.createElement('div')
div.className='item'
div.textContent=item.text
list.appendChild(div)
})
})
}
function handleScroll(){
if(list.scrollTop + list.clientHeight >=list.scrollHeight-10){
page++
loadMoreData()
}
}
list.addEventListener('scroll',handleScroll)
loadMoreData(page)
</script>
</body>
</html>
用户在页面顶部向下拉时,触发页面重新渲染
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id='refreshIndicator'></div>
<div id="list"></div>
<script>
const list = document.getElementById('list')
const refreshIndicator = document.getElementById('refreshIndicator')
let startY = 0
let isPulling = false
function loadMoreData(page) {
return fetch(`https://example.com/api/data?page=${page}`)
.then(response => response.json())
.then(data => {
list.innerHTML = ''
data.item.forEach(item => {
const div = document.createElement('div')
div.className = 'item'
div.textContent = item.text
list.appendChild(div)
})
refreshIndicator.style.display='none'
}
}
list.addEventListener('touchstart',event=>{
if(list.scrollTop === 0){
startY=event.touches[0].pageY
isPulling=true
}
})
list.addEventListener('touchmove',event=>{
if(isPulling){
const currentY=event.touches[0].pageY
if(currentY>startY){
refreshIndicator.style.display='block'
refreshIndicator.style.height=`${currentY -startY}px`
}
}
})
list.addEventListener('touchend',()=>{
if(isPulling){
const refreshHeight=parseInt(refreshIndicator.style.height,10)
if(refreshHeight>50){
loadData()
}else{
refreshIndicator.style.display='none'
}
isPulling=false
refreshIndicator.style.height='50px'
}
})
loadMoreData(page)
</script>
</body>
</html>