Javascript 页面自动上下滚动

Javascript page scrolls automatically up and down

我正在努力应对一个超出我的技能范围的挑战。我试图让页面在无限循环中上下滚动(非常缓慢)。我让代码循环一次,但我的挑战是让它一遍又一遍地循环。我希望得到建议。

do {
$(document).ready(function(){
     $('body,html').animate({scrollTop: 2650}, 57820);
  
});

$(document).ready(function(){
     $('body,html').animate({scrollTop: 0}, 35000);
  
});
}
while (true === true);

Javascript代码主要是asynchronous。这对您来说意味着浏览器是 运行 快速“转到顶部”和“转到底部”代码。从而使您的浏览器崩溃。你想要的是等到滚动到底部完成,然后滚动到顶部。这是一个可以满足您要求的示例。

// Getting a reference to html. The way you did it in the loop
// is slow because it has to get access to it every time.
const main = $('html');

// The scrollTop function
// scrolls to the top
function scrollTop() {
    console.log('scrolling to top')
    main.animate({scrollTop: 0},1000,"linear",scrollBottom /* this is a callback it means when we are done scrolling to the top, scroll to the bottom */)
}

function scrollBottom() {
    console.log('scrolling to bottom')
    main.animate({scrollTop: document.body.offsetHeight},1000,"linear",scrollTop /* this is a callback it means when we are done scrolling to the bottom, scroll to the top */)
}

// this kicks it off
// again only running $(document).ready once to increase performance.
// Once scrollTop completes, it calls scrollBottom, which in turn calls scrollTop and so on
$(document).ready(scrollTop);

Javascript 不会等到一个函数完成,所以你不能创建这样的循环。但是您可以利用 jquery.animate 完整的功能:

$(document).ready(scrollDown()); //run function first time

function scrollUp() {
 $('body,html').animate({
   scrollTop: 0
 }, 35000, "linear", 
   scrollDown//we are on the top, let's go down 
 );
 return false;
}

function scrollDown() {
 $('body,html').animate({
   scrollTop: $(document).height()
 }, 57820, "linear",
   scrollUp//scrolling down is completed, let's go up
  );
}

这是此代码的工作示例:https://jsfiddle.net/y7fguk52/