jQuery使用.next()循环滚动元素至顶部仅首项生效如何解决
问题根因
代码没有记录当前滚动位置的状态:每次定时器触发时,都固定选取DOM结构中排在第一位的.per-account元素,再查找它的下一个相邻元素,这个相邻元素永远是第二个蓝色块,因此滚动永远停在第二个元素,无法继续向后遍历。
修复代码
首先提前缓存所有待滚动的元素集合,维护一个索引变量标记当前滚动到的元素位置,每次定时器触发时更新索引,到集合末尾就重置索引到0实现循环:
$(function() { // 缓存所有滚动目标元素,初始化当前位置索引 const $accountList = $('.per-account'); let activeIndex = 0; setInterval(function() { // 索引自增,通过取模运算实现末尾回到开头的循环逻辑 activeIndex = (activeIndex + 1) % $accountList.length; $('html, body').animate({ scrollTop: $accountList.eq(activeIndex).offset().top }, 1000); }, 3000) });
原有HTML结构无需修改,可直接复用:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="per-account" style="height: 500px; width: 100%; background: red;"> </div> <div class="per-account" style="height: 500px; width: 100%; background: blue;"> </div> <div class="per-account" style="height: 500px; width: 100%; background: orange;"> </div> <div class="per-account" style="height: 500px; width: 100%; background: green;"> </div>
优化点说明
- 提前缓存DOM元素集合,避免定时器每次触发都重复查询DOM,减少性能消耗
- 用取模运算
%处理索引循环,不需要额外写if/else判断是否到达元素列表末尾,逻辑更简洁 - 如果需要页面加载完成后立刻从第一个元素开始滚动,只需要把初始
activeIndex的值改为-1即可
内容的提问来源于stack exchange,提问作者Vivian Onuagu
相关产品推荐
相关产品推荐

