Javascript detect browser scroll to the top?

2019-02-23 17:52发布

How do I modify the following code to detect scrolling to the top page instead.

window.onscroll = function(ev) {
    if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
        alert(bottom);
    }
};

EDIT:

I am working on IE 10 for Windows Phone 8 BTW

5条回答
干净又极端
2楼-- · 2019-02-23 18:29

Managed to figure it out. Here's my code

window.onscroll = function() {

    var body = document.body; //IE 'quirks'
    var document = document.documentElement; //IE with doctype
    document = (document.clientHeight) ? document : body;

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

DEMO

查看更多
相关推荐>>
3楼-- · 2019-02-23 18:36
if (document.body.scrollTop == 0 || document.documentElement.scrollTop == 0) 
{
    alert("top");
}

worked for me

https://www.w3schools.com/jsref/event_onscroll.asp

查看更多
Luminary・发光体
4楼-- · 2019-02-23 18:41

The best way to do this with only JS is the following example adding an event listener:

var el = document.getElementById('PUT_YOUR_TOP_ELEMENT_ID_HERE');
el.addEventListener('scroll', function(event) {
    if (event.target.scrollTop === 0) {
        alert('Top of page detected');
    }
}, false);
查看更多
放荡不羁爱自由
5楼-- · 2019-02-23 18:42

its really simple:

$(window).on('scroll', function () {
  let scrollAmount = window.scrollY;
  console.clear()
  console.log(scrollAmount)
});
查看更多
唯我独甜
6楼-- · 2019-02-23 18:53

window.scrollY is not cross-browser according to MDN. On IE<9 you must check document.body.scrollTop, as no property of window will give you the current scroll position. Actually, document.body.scrollTop is what I use most frequently, as in my experience it just works.

查看更多
登录 后发表回答