16

我想在滚动到达页面底部时发出警报,如下所示:

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

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

4

5 回答 5

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

JSFiddle在这里:http: //jsfiddle.net/cSer6/

于 2013-09-30T19:44:58.553 回答
4

这在 IE 中对我有用

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

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

于 2014-11-01T16:08:19.390 回答
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');
    }
}

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

在 chrome 17/18、safari 5、ff 10/11.0 即 7-9 中使用http://browserling.com进行了测试

于 2012-04-08T02:29:45.517 回答
2
document.onscroll = function() {
    if(!document.body.scrollTop){
        alert('top');
    }
}

JSFiddle演示

于 2012-04-08T02:22:33.857 回答
-2
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 兼容:8、7、5)和 Opera 11.60 上成功测试。

于 2012-04-08T22:14:04.093 回答