【发布时间】:2015-12-22 05:27:37
【问题描述】:
在我当前从一个 div 滚动到另一个 div 的解决方案中,我支持 previous 和 next。
这可以通过保存上次滚动到的 div 的索引来确定下一个滚动到的位置。但是,当用户使用滚轮滚动时,这会中断。我想知道是否有办法计算哪个 div 最接近窗口顶部,然后确定下一个滚动到哪个索引。
这反过来会消除我遇到的问题。
使用我当前的解决方案测试错误:
- 转到 jsfiddle 链接
- 单击向下箭头两次。它应该从一个 div 滚动到下一个。
- 接下来,使用鼠标滚轮向下滚动页面的 3/4。
- 现在再次点击向下箭头。您会看到它会带您回到上次离开时的顶峰。
http://jsfiddle.net/JokerMartini/yj9pvz2a/1/
var curr_el_index = 0;
var els_length = $(".section").length;
$('.btnNext').click(function () {
curr_el_index++;
if (curr_el_index >= els_length) curr_el_index = 0;
$("html, body").animate({
scrollTop: $(".section").eq(curr_el_index).offset().top - 20
}, 700);
});
$('.btnPrev').click(function () {
curr_el_index--;
if (curr_el_index < 0) curr_el_index = els_length - 1;
$("html, body").animate({
scrollTop: $(".section").eq(curr_el_index).offset().top - 20
}, 700);
});
【问题讨论】: