判断浏览器是否滑到底部


想要判断滚动条是否滑到底部,会用到下面三个属性

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 是浏览器可视范围内的高度,如下图所示,
判断滚动条是否滑到底部 scrollHeigt==clientHeight+scrollTop

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浏览器有毒

相关文章: