JS实现滚动条触底加载更多

JavaScript015

JS实现滚动条触底加载更多,第1张

原理

1.通过监听滚动区域DOM的scroll事件, 计算出触底

// 滚动可视区域高度 + 当前滚动位置 === 整个滚动高度

scrollDom.clientHeight + scrollDom.scrollTop === scrollDom.scrollHeight

2.触底后触发列表添加, 列表添加使用createDocumentFragment, 将多次插入的DOM先存入内存, 最后一次填充进去, 提高性能, 也方便后面的MutationObserver监听

3.使用MutationObserver监听列表的DOM添加, 添加完毕后, 隐藏加载中提示

示例

https://codepen.io/klren0312/full/dybgayL

参考资料

https://developer.mozilla.org/zh-CN/docs/Web/API/Element/clientHeight

https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollHeight

https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollTop

https://developer.mozilla.org/zh-CN/docs/Web/API/GlobalEventHandlers/onscroll

https://developer.mozilla.org/zh-CN/docs/Web/API/Document/createDocumentFragment

https://developer.mozilla.org/zh-CN/docs/Web/API/MutationObserver

<!DOCTYPE=html>

<html>

<head>

<script src="js/jquery.js" type="text/javascript"></script>

<script type="text/javascript">

$(document).ready(function(){

var range = 50//距下边界长度/单位px

var elemt = 500 //插入元素高度/单位px

var maxnum = 20 //设置加载最多次数

var num = 1

var totalheight = 0

var main = $("#content")//主体元素

$(window).scroll(function(){

var srollPos = $(window).scrollTop() //滚动条距顶部距离(页面超出窗口的高度)

//console.log("滚动条到顶部的垂直高度: "+$(document).scrollTop())

//console.log("页面的文档高度 :"+$(document).height())

//console.log('浏览器的高度:'+$(window).height())

totalheight = parseFloat($(window).height()) + parseFloat(srollPos)

if(($(document).height()-range) <= totalheight &&num != maxnum) {

main.append("<div style='border:1px solid tomatomargin-top:20pxcolor:#ac"+(num%20)+(num%20)+"height:"+elemt+"' >hello world"+srollPos+"---"+num+"</div>")

num++

}

})

})

</script>

</head>

<body>

<div id="content" style="height:960px">

<div id="follow">this is a scroll test<br/> 页面下拉自动加载内容</div>

<div style='border:1px solid tomatomargin-top:20pxcolor:#ac1height:800' >hello world test DIV</div>

</div>

</body>

</html>

1、首先新建一个html文件,命名为test.html,在test.html文件内,引入jquery.min.js库文件,成功加载该文件,才能使用jquery中的方法。

2、在test.html文件内,使用button标签创建一个按钮,按钮名称分别为“刷新页面”。

3、在test.html文件内,设置button标签的id为btn,主要用于下面通过该id获得button对象。

4、在js标签内,使用$(function(){ })方法在页面加载完成时,通过window.location.href获得当前页面的链接,并把链接保存在变量url中。

5、在js标签内,通过id(btn)获得button对象,给它绑定click点击事件,实现当按钮被点击时,使用window.location.href方法跳转至url,从而实现刷新页面的效果。

6、在浏览器打开test.html文件,点击按钮,查看实现的效果。