javascript - How do i detect when a user is at the top of the webpage

前端 未结 3 1818
遇见更好的自我
遇见更好的自我 2021-01-23 08:02

I\'m pretty much completely new to javascript, and I know there\'s already a similar question to this on here, but i would like the script as in.

if (user is at top of

3条回答
  •  轮回少年
    2021-01-23 08:49

    Here's a clean solution that should make sense if you're new to JS:

    //call your function on scroll
    window.onscroll = myScrollFunction;
    
    function myScrollFunction(){
      if(getYOffset() == 0){
        //if at top, do this
        alert('bingo');
    
      }
    };
    //helper function (since ie handles scrolling different than firefox)
    function getYOffset() {
        var pageY;
        if(typeof(window.pageYOffset)=='number') {
           pageY=window.pageYOffset;
        }
        else {
           pageY=document.documentElement.scrollTop;
        }
        return pageY;
    }
    

提交回复
热议问题