检测滚动何时到达页面底部 [ 没有 jQuery]

Detect when Scroll reaches the BOTTOM of the page [ without jQuery ]

本文关键字:底部 没有 jQuery 滚动 何时 检测      更新时间:2023-09-26

我想在滚动到达页面底部时提醒一些东西,如下所示:

$(function(){
  $(document).scroll(function() {
    if($(document).scrollTop() == 0) alert("top");
  })
})

但是没有jQuery,并在到达底部时发出警报。

document.addEventListener('scroll', function (event) {
    if (document.body.scrollHeight == 
        document.body.scrollTop +        
        window.innerHeight) {
        alert("Bottom!");
    }
});

JSFiddle here: http://jsfiddle.net/cSer6/

if(window.addEventListener){
    window.addEventListener('scroll',scroll)
}else if(window.attachEvent){
    window.attachEvent('onscroll',scroll);
}
function scroll(ev){
    var st = Math.max(document.documentElement.scrollTop,document.body.scrollTop);
    if(!st){
            console.log('top');
    }else if((st+document.documentElement.clientHeight)>=document.documentElement.scrollHeight ){
           console.log('bottom');
    }
}

示例:http://jsfiddle.net/ampersand/AEnzJ/

在Chrome 17/18,Safari 5,FF 10/11.0,IE 7-9中使用 http://browserling.com 进行测试

在IE中对我有用

document.onscroll = function() {
    if(document.documentElement.scrollTop + window.innerHeight == document.documentElement.scrollHeight)
    {
        alert('bottom');
    }
}

http://jsfiddle.net/cSer6/46/

document.onscroll = function() {
    if(!document.body.scrollTop){
        alert('top');
    }
}

JSFiddle 演示

if (document.body.scrollHeight <= Math.ceil(window.pageYOffset + window.innerHeight)) {

这在勇敢中起作用了。

function addEvent(node, type, callback) {
    if('addEventListener' in node) {
        node.addEventListener(type, callback, false);
    } else {
        node.attachEvent('on' + type, callback);
    }
}
addEvent(window, 'scroll', (function() {
    // https://developer.mozilla.org/en/DOM/window.scrollY#Notes
    var stObj, stProp;
    if('scrollY' in window) { // CSSOM:
        // http://www.w3.org/TR/cssom-view/#extensions-to-the-window-interface
        stObj = window;
        stProp = 'scrollY';
    } else if('pageYOffset' in window) { // CSSOM too
        stObj = window;
        stProp = 'pageYOffset';
    } else {
        stObj = document.documentElement.clientHeight ?
            document.documentElement : document.body;
        stProp = 'scrollTop';
    }
    var node = document.documentElement.clientHeight ?
        document.documentElement :
        document.body; // let's assume it is IE in quirks mode
    var lastSt = -1;
    return function(e) {
        if(lastSt !== stObj[ stProp ] && // IE <= 8 fires twice
           node.scrollHeight === stObj[ stProp ] + node.clientHeight) {
            alert('bottom');
        }
        lastSt = stObj[ stProp ];
    };
})());

它已成功通过Firefox 11,Chrome 17,IE 9(X-UA-Compatible:8,7,5)和Opera 11.60进行了测试。