Javascript detect browser scroll to the top?

2019-02-23 17:56发布

问题:

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

回答1:

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



回答2:

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.



回答3:

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


回答4:

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

worked for me

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



回答5:

its really simple:

$(window).on('scroll', function () {
  let scrollAmount = window.scrollY;
  console.clear()
  console.log(scrollAmount)
});