Detect when Scroll reaches the BOTTOM of the page

2019-01-22 09:29发布

问题:

I want to alert something when the scroll reaches the BOTTOM of the page, like this:

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

But without jQuery, and alert when reaches the Bottom.

回答1:

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

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



回答2:

This is working for me in IE

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

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



回答3:

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

JSFiddle demo



回答4:

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');
    }
}

example: http://jsfiddle.net/ampersand/AEnzJ/

tested with http://browserling.com in chrome 17/18, safari 5, ff 10/11.0, ie 7-9



回答5:

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 ];
    };
})());

It's successfully tested with Firefox 11, Chrome 17, IE 9 (X-UA-Compatible: 8, 7, 5) and Opera 11.60.