监控滚动条距离底部的位置

4,123 阅读1分钟

为了实现一个滚动条距离底部一定距离时候,某个元素实现显示和隐藏的效果。

首先看document.body.clientHeight VS document.documentElement.clientHeight

以下蓝色区域div高度为500px,因为不会出现滚动条,所以此时不会触发window.scroll事件:

当摆放三个同样高度的div后,出现了滚动条:

获取窗口可视范围的高度

function getViewHeight(){  
    return document.documentElement.clientHeight;  
}

获取滚动条距离顶部的距离

function getScrollTop(){  
    return document.documentElement.scrollTop;  
}

获取文档内容实际高度

function getContentHeight(){  
    return Math.max(document.body.scrollHeight,document.documentElement.scrollHeight);  
}

在window上添加监听onscroll事件

window.onscroll=function(){
    // 浏览器可见区域高度为:
    var viewHeight=getViewHeight(),
    // 窗口滚动条高度
    scrollHeight=getScrollTop(),
    // 文档内容实际高度:
    contentHeight=getContentHeight(),
    // 滚动条距离底部的高度
    scrolllBtmHeight=contentHeight-scrollHeight-viewHeight;
    console.log('浏览器可见区域高度为:'+viewHeight+' 文档内容实际高度:'+contentHeight+' 滚动条距离顶部的高度为:'+scrollHeight+' 滚动条距离底部的高度为:'+scrolllBtmHeight);
}

在chrome与Safari下每滑动一下鼠标滚轮,滚动条移动4px

在firefox下每滑动一下鼠标滚轮,滚动条移动16px

目前不知道如何控制不同浏览器下滚动距离相同,之后再更。

参考文档

www.cnblogs.com/iyitong/p/4…