简体   繁体   中英

function scrollPage() does not work on mobile devices

I have a function in javascript that needs to scroll the page up and down until the user presses a button to disable it. Here is my current function:

var scrollDirection = 1;
function scrollPage() {
  if (isScrollMode) {
    window.scrollBy(0, scrollDirection); // horizontal and vertical scroll increments
    scrolldelay = setTimeout('scrollPage()', 50); // scrolls every 50 milliseconds
    if (window.pageYOffset == 0) {
      scrollDirection = 1;
    } else if (window.pageYOffset == document.body.scrollHeight - window.innerHeight) {
      scrollDirection = -1;
    }
  }
}

So far this method works on a computer, however, when I tested this function on my google chrome web browser on my phone, it only went down and not up. Once it reaches the end of the page, it stays there. Can anyone tell me why? I appreciate any help!

It's because window.pageYOffset return a float, in my case 78.4000015258789 and document.body.scrollHeight - window.innerHeight return a integer, in my case 79 . Then, (78.4000015258789 == 79) = false

What you can change is to add one to window.pageYOffset to get 79.4 and check if window.pageYOffset > (document.body.scrollHeight - window.innerHeight)

Here is the edited code (must be working):

 var scrollspeed = 10; var scrollDirection = scrollspeed; function scrollPage() { if (isScrollMode) { window.scrollBy(0, scrollDirection); // horizontal and vertical scroll increments scrolldelay = setTimeout("scrollPage()", 50); // scrolls every 50 milliseconds if (window.pageYOffset == 0) { scrollDirection = scrollspeed; } else if ( window.pageYOffset + 1 > document.body.scrollHeight - window.innerHeight ) { //window.pageYOffset return a float scroll y value, for exemple in my case 78.4000015258789; //We add +1 to obtain 79.4 //(document.body.scrollHeight - window.innerHeight) return a interger of 79 scrollDirection = -scrollspeed; } } } let isScrollMode = true; scrollPage();
 <p>Lorem</p> <p>Lorem</p> <p>Lorem</p> <p>Lorem</p> <p>Lorem</p> <p>Lorem</p> <p>Lorem</p> <p>Lorem</p> <p>Lorem</p> <p>Lorem</p> <p>Lorem</p> <p>Lorem</p> <p>Lorem</p> <p>Lorem</p> <p>Lorem</p> <p>Lorem</p> <p>Lorem</p> <p>Lorem</p> <p>Lorem</p> <p>Lorem</p> <p>Lorem</p> <p>Lorem</p> <p>Lorem</p> <p>Lorem</p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM