使滚动功能下降设定的次数,然后备份

问题描述:

所以这应该是非常简单的我猜,但我是新来的这个,我得到了错误的代码只运行两次,或滚动两次而不是我需要的任何数字,然后结束。使滚动功能下降设定的次数,然后备份

scrNum是每次脚本在某个页面上运行时都会有所不同的数字,我在页面加载时得到它,它通常是一个小数字。

也有更简单的方法来做到这一点与jQuery也许?

var i = 0; 
function scroll(){ 

    setTimeout(function(){ 

     //scroll to the bottom of page 
     window.scrollTo(0, document.body.scrollHeight); 


     //if less than needed execute again 
     if(i < scrNum){ 
      i++; 
      scroll(); 
     } else 
      window.scrollTo(0, document.head.scrollHeight); 

    }, 2000); 

} 
+0

好了,你自己说的,'scrNum'等于少数(我猜> 0),当你进入的setTimeout,您滚动一次,然后你再滚动,因为'scrNum> 0',' scrNum'可能为1,这就是为什么你只运行两次而不是更多,编辑:你可以告诉我们你真正想要发生的事情,所以我们可以帮助你更多。 –

+0

scrNum通常在3-6之间。我想在页面加载时滚动到底部等于scrNum的次数,它应该每2秒滚动一次,并在结束时滚动回到最佳。 – PredatorIWD

此代码应该工作,请注意,可能有更好的方法来获得你想要的位置,我只是做了一般的身体标记。

var i = 0; 

var myInterval = setInterval(function() { 
    if (i < scrNum) { //check if you need to scroll 
    $(window).scrollTop($('body').height()); // scroll to the bottom of body (== the height of body) 
    i++; 
    } else { 
    $(window).scrollTop($('body').offset().top); //if you did all the scrolls that needed, scroll to the top of body 
    clearInterval(myInterval); // IMPORTANT- clear the interval that running. 
    } 
}, 2000);