判斷滾動條是否滑到底部 scrollHeigt==clientHeight+scrollTop
阿新 • • 發佈:2018-11-04
判斷瀏覽器是否滑到底部
文章目錄
想要判斷滾動條是否滑到底部,會用到下面三個屬性
1、scrollHeigt
scrollHeigt 是整個html下的div總高度,舉個例子。
<div class="box1"></div>
<div class ="box2"></div>
<div class="box3"></div>
div{
height:300px
}
上述程式碼中的三塊div總高度是900,所以,scrollHeigt 就位900
2、clientHeight
clientHeight 是瀏覽器可視範圍內的高度,如下圖所示,
3、scrollTop
scrollTop 是當你滑動滑鼠滾輪看一個網頁的時候,被上面的瀏覽器視窗捲進去的高度,舉個例子
<div class="container1"></div>
<div class="container2" ></div>
<div class="container3"></div>
.container1 {
height: 300px;
width: 100%;
background: red;
}
.container2 {
height: 300px;
width: 100%;
background: yellow;
}
.container3 {
height: 300px;
width: 100%;
background: blue;
}
* {
margin: 0;
padding: 0;
}
這三個div,高度分別是300px,一共是900px,在瀏覽器開啟時,滑動滾輪,當第一個div完全消失不見的時候,被瀏覽器捲進去了的時候,這時的scrollTop正好是300,當第二個div被捲進去時,scrollTop就變成了600,以此類推。所以說scrollTop就是被瀏覽器捲進去div的高度。
4、scrollHeigt == clientHeight + scrollTop
所以,當scrollHeigt 等於clientHeight 與scrollTop的相加的和時,代表著正正好好滾動條滑動到了底部,大白話總結:
被瀏覽器捲進去的所有div的高度,再加上最後沒有被捲進去的div(就是你最後看到的可視視窗內的div),正好等於整個html的高度時,滾動條就滾不動了。尋思尋思,就是這個理!
5、程式碼實現
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.container1 {
height: 300px;
width: 100%;
background: red;
}
.container2 {
height: 300px;
width: 100%;
background: yellow;
}
.container3 {
height: 300px;
width: 100%;
background: blue;
}
* {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div class="container1"></div>
<div class="container2"></div>
<div class="container3"></div>
<script>
window.onscroll = ()=>{
console.log('可視高度'+document.documentElement.clientHeight);
console.log('總高度'+document.documentElement.scrollHeight);
console.log('捲進去的高度:'+document.documentElement.scrollTop);
let cHeight = document.documentElement.clientHeight;
let sHeight = document.documentElement.scrollHeight;
let sTop = document.documentElement.scrollTop;
if(sHeight == cHeight+ sTop) {
console.log('你不可以在滾了,到頭了!');
}
}
</script>
</body>
</html>
建議用火狐瀏覽器嘗試,google瀏覽器有毒