我正在努力应对一个有点超出我的技能范围的挑战。我试图使页面无限循环地上下滚动(非常缓慢)。我让代码循环一次,但我的挑战是让它一遍又一遍地循环。我很乐意提供建议。
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页面自动上下滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66252655/