該判斷是實現(xiàn)頁面滾動到底部自動加載更多功能的必要條件芥吟,先看代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>scorll</title>
<style>
.main {
background-color: red;
height: 3000px;
}
.bottom {
background-color: black;
height: 30px;
}
</style>
</head>
<body>
<div class="main">
</div>
<div class="bottom">
</div>
<script type="text/javascript">
// ...
</script>
</body>
</html>
.bottom
在頁面底部,現(xiàn)在添加js代碼來判斷頁面是否滾動到 .bottom
元素
方法一
使用 getBoundingClientRect()
來判斷位置
window.onload = function() {
var windowHeight = document.documentElement.clientHeight // 視窗高度-也就是瀏覽器可視區(qū)域高度
var threshold = 20 // 可以指定提前加載的距離
var lock = false // 如果到達指定位置汤善,則不再執(zhí)行打印log
window.addEventListener('scroll', function() {
// getBoundingClientRect()-得到矩形元素的界線
// 返回的是一個對象,包含 top, left, right, 和 bottom四個屬性值
// 大小都是相對于文檔視圖()瀏覽器可視區(qū)域)左上角計算而來
var targetRect = document.getElementsByClassName('bottom')[0].getBoundingClientRect()
//getBoundingClientRect()的top屬性-目標(biāo)元素離視窗頂部的距離
var targetTop = targetRect.top
if(lock) {
return
} else {
// 如果目標(biāo)元素離視窗頂部的距離小于視窗高度
// 則表示已滾動到目標(biāo)元素位置
if(targetTop < (windowHeight + threshold)) {
lock = true
console.log('bottom')
}
}
})
}
方法二
使用 scrollTop
、offsetTop
來判斷位置
window.onload = function() {
var windowHeight = document.documentElement.clientHeight
var threshold = 20 //指的是提前加載的距離
var lock = false
window.addEventListener('scroll', function() {
var scrollBarTop = document.body.scrollTop // 滾動條離頁面頂端的距離
var targetTop = document.getElementsByClassName('bottom')[0].offsetTop // 目標(biāo)元素離頁面頂端的距離
// 如果目標(biāo)元素離頁面頂端的距離小于視窗高度+滾動條離頁面頂端的距離
// 則表示已滾動到目標(biāo)元素位置
if(lock) {
return
} else {
if(targetTop < (windowHeight + scrollBarTop + threshold)) {
lock = true
console.log('bottom')
}
}
})
}