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

2019-03-02 16:59发布

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 page) { (execute this function) }

Thanks in advance

3条回答
放我归山
2楼-- · 2019-03-02 17:28

I'm using a function to make it cross-browser compatible that can be found here: Cross-browser method for detecting the scrollTop of the browser window

function getScrollTop(){
    if(typeof pageYOffset!= 'undefined'){
        //most browsers
        return pageYOffset;
    }
    else{
        var B= document.body; //IE 'quirks'
        var D= document.documentElement; //IE with doctype
        D= (D.clientHeight)? D: B;
        return D.scrollTop;
    }
}

if(!getScrollTop()){
   // user is at the top
}

Here is a little demo: http://jsfiddle.net/uDS4n/1/

查看更多
疯言疯语
3楼-- · 2019-03-02 17:36

This is a little snippet I use to determine the scrolltop of a page, I can't remember where I got it, or whether I wrote it myself so can't credit it.

var st=0;
if(typeof pageYOffset!= 'undefined'){
    //most browsers
    st = pageYOffset;
} else {
    var B = document.body; //IE 'quirks'
    var D = document.documentElement; //IE with doctype
    D = (D.clientHeight)? D: B;
    st = D.scrollTop;
}

if st==0 then the user is at the top of the page!

查看更多
小情绪 Triste *
4楼-- · 2019-03-02 17:48

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;
}
查看更多
登录 后发表回答