jquery - 到达正文末尾后,向下滚动不会重复

标签 jquery css

我试图从 div 的拳头再次重复滚动,但它只在页面加载时工作一次。

<div class="content">
  <div class="next-section blue">First Section</div>
  <div class="next-section red">Second Section</div>
  <div class="next-section green">Second Section</div>
  <div class="next-section yellow">Second Section</div>
</div>
<button class="down-btn">Click to go to the next section</button>
var i = 0;
$('.down-btn').on('click', function(e) {
  e.preventDefault();
  i++;
  var offset = $("div.next-section").eq(i).offset().top;
  $('html, body').stop().animate({
    scrollTop: offset
  }, 400);
});

所以,当滚动结束时,点击这个按钮,应该会从第一部分重新开始 链接:https://jsfiddle.net/uj91djeL/1/

最佳答案

你应该在索引变量 i 到达末尾时将其重置为 0,即等于所有部分的长度。

var i = 0;
$('.down-btn').on('click', function(e) {
  e.preventDefault();
  i++;
  var nextSection$ = $("div.next-section") 
  if(i === nextSection$.length) i=0;
  var offset = nextSection$.eq(i).offset().top;
  $('html, body').stop().animate({
    scrollTop: offset
  }, 400);
});

检查 this fiddle

关于jquery - 到达正文末尾后,向下滚动不会重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58000198/

相关文章:

javascript - 在我的案例中,如何访问从 AJAX 回调函数外部的 ajax 调用返回的数据?

html - 尝试设置按钮样式但不起作用

javascript - 如何防止双击时在 HTML5 Canvas 外选择文本?

JavaScript 验证比较 intime 和 outtime?

html - CSS Div 对齐问题

javascript - 如何制作具有垂直滚动效果的菜单按钮

php - TCPDF 使内容跳转一页

javascript - jQuery - ui.keyCode.TAB

javascript - 在类名末尾添加一个整数

javascript - 当 Kendo ComboBox 的数据源返回空时显示消息