js监听页面滚动条

TOC

js监听页面滚动条

使用scroll()方法

https://www.w3school.com.cn/jquery/event_scroll.asp

当页面滚动条变化时,执行的函数:

$(window).scroll(function () {....});
或
$(selector).scroll(function)//function非必须

案例

旧版本

旧版本可以使用bind/unbind方法

// 页面渲染完之中执行的代码
$(function(){
    // 绑定事件,监听滚动条下拉的动作
    bindScrollEvent();
});
function bindScrollEvent(){
    // 添加滚动监听事件
    $(window).scroll( function() {
        var docHeight = $(document).height(); // 获取整个页面的高度(不只是窗口,还包括为显示的页面)
        var winHeight = $(window).height(); // 获取当前窗体的高度(显示的高度)
        var winScrollHeight = $(window).scrollTop(); // 获取滚动条滚动的距离(移动距离)
        //还有30像素的时候,就查询
        if(docHeight == winHeight + winScrollHeight){
            //到底(一般是离到底还有一段距离就查询的)
        }
    });
}


//移除监听
$(window).unbind("scroll");

新版本

function doSth () {
    // do something
}
// 绑定scroll事件
$(window).on('scroll', doSth);
// 解绑scroll事件
$(window).off('scroll', doSth);




posted @ 2020-01-14 16:22  紫月java  阅读(11328)  评论(0编辑  收藏  举报