思路:当可视区域+卷起来的部分>=网页的高度,说明网页滚动到了底部;当卷上去的部分为0说明网页滚动到顶部了。
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>网页滚动到顶部或者底部</title>
<style>
body,
div {
margin: 0;
padding: 0;
}
div {
width: 300px;
height: 300px;
background-color: aqua;
margin: 1000px auto 100px auto;
}
</style>
</head>
<body>
<div></div>
<script>
function scrollBottomOrTop() {
var clients = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
var scrollTop = document.documentElement.scrollTop;
// 这里存在兼容问题,会把body当成div来处理,如果用document.body.scrollHeight就得不到正确的高度,用body时需要把doctype后面的html去掉
// 这里没用body,而是用到documentElement
var wholeHeight = document.documentElement.scrollHeight;
if (clients + scrollTop >= wholeHeight) {
alert("我到底部了");
// 在实际应用中可以通过请求后台获取下一页的数据,然后显示到当前位置,就能达到按页加载的效果。
}
if (scrollTop == 0) {
alert("我到顶部了");
}
}
window.onscroll = scrollBottomOrTop;
</script>
</body>
</html>
结果:还是没法弄进来,这里就是滚到底部会弹出来“我到底部了”,滚到顶部会弹出来“我到顶部了”。
用途:可以实现按页加载哦~
ps:这个好像实现了各种兼容