[removed] check IF page is at top

2019-02-17 00:59发布

问题:

Is there a way to check, with javascript, if the page is at scroll(0,0)?

Reason being I've got a full page slider that I need to pause the second the page is not at origin.

And it might not necessarily be because the page is being scrolled live as I've got internal HTML # links that would load the page right to a scrolled point without actually scrolling.

So the check needs to be is the page not at the top, as opposed to, has the page been scrolled.

回答1:

Try this:

document.body.scrollTop === 0


回答2:

i think you can get the position using jQuery $(window).scrollTop();



回答3:

You can check if window.scrollY (the number of pixels the window has scrolled vertically) is equal to 0. If you want to check if the window has been scrolled to its leftermost, you can check if window.scrollX (the number of pixels the window has scrolled horizontally) is equal to 0. If you combine the two, it will ensure the the window is at (0,0) position.

if(window.scrollY==0){
 //user scrolled to the top of the page
}
if(window.scrollX==0){
 //user scrolled to the leftmost part of the page
}
if(window.scrollY==0&&window.scrollX==0){
  //user scrolled to the leftmost part of the top of the page—i.e., they are at position (0, 0)
}

Demo:

html, body{
  height: 3000px;
  position: relative;
  margin: 0;
}
<div style="position: absolute; width: 100%; top: 0; left: 0; right: 0px; background-color: dodgerblue; text-align: center;">
Header
</div>
<button style="position: fixed; right: 0; bottom: 0; display: none;" onClick="window.scroll({top: 0, left: 0, behavior: 'smooth'})">
Back To Top
</button>
<div style="position: absolute; width: 100%; bottom: 0; left: 0; right: 0px; background-color: dodgerblue; text-align: center;">
Footer
</div>
<script>
var goToTop = document.querySelector('button');
window.addEventListener("scroll", function(){
  if(window.scrollY==0){
    //user is at the top of the page; no need to show the back to top button
    goToTop.style.display = "none";
  } else {
    goToTop.style.display = "block";
  }
});
</script>

For better browser compatibility, use window.pageYOffset instead of window.scrollY and window.pageXOffset instead of window.scrollX.

The following code can be used in cases when full browser compatability is necessary (i.e., IE < 9):

var x = (window.pageXOffset !== undefined)
  ? window.pageXOffset
  : (document.documentElement || document.body.parentNode || document.body).scrollLeft;
//number of pixels scrolled horizontally (work with this value instead of window.scrollX or window.pageXOffset

var y = (window.pageYOffset !== undefined)
  ? window.pageYOffset
  : (document.documentElement || document.body.parentNode || document.body).scrollTop;
//number of pixels scrolled vertically (work with this value instead of window.scrollY or window.pageYOffset