如何使用开始停止按钮按需启动自动滚动网页

时间:2018-07-06 09:44:01

标签: javascript animation autoscroll

我正在尝试获取可自动滚动我的网页的脚本,以便按启动和停止按钮按需启动,请帮忙

//run instantly and then goes after (setTimeout interval)

$("html, body").animate({
  scrollTop: $(document).height()
}, 50000);
setTimeout(function() {
  $('html, body').animate({
    scrollTop: 0
  }, 50000);
}, 50000);
setInterval(function() {
  // 50000 - it will take 4 secound in total from the top of the page to the bottom
  $("html, body").animate({
    scrollTop: $(document).height()
  }, 50000);
  setTimeout(function() {
    $('html, body').animate({
      scrollTop: 0
    }, 50000);
  }, 50000);

}, 50000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

1 个答案:

答案 0 :(得分:0)

此代码创建scroll JavaScript变量(作为setInterval()函数)并运行它。该功能将每2秒(2000毫秒)滚动页面。您可以通过更改此值来调整自动滚动速度。向下滚动高度是由scrollBy()的第二个参数-1000定义的;窗口将向下滚动1000像素。

function start_scroll_down() { 
   scroll = setInterval(function(){ window.scrollBy(0, 1000); console.log('start');}, 1500);
}

function stop_scroll_down() {
   clearInterval(scroll);
   console.log('stop');
}
<button onclick="start_scroll_down();">Start Scroll</button>
<button onclick="stop_scroll_down();">Stop Scroll</button>