我有一个如下的结构来创建一个单页 Web 应用程序,使用一些滚动功能:
<div class="home_section"></div> <!-- 1 -->
<div class="home_section"></div> <!-- 2 -->
<div class="home_section"></div> <!-- 3 -->
<div class="home_section"></div> <!-- 4 -->
当滚动事件开始时,我需要滚动到上述每个 DIV。
因此,例如,当滚动开始时,如果从顶部可见的第一个 DIV 是 <!-- 2 -->
,正文必须滚动到 DIV <!-- 3 -->
自动。
这就是我正在做的事情:
if ($(this).attr('id') == 'home') {
$(document).on("scrollstart", function (e) {
console.log('scrolling started on home');
e.preventDefault();
var next = $(this).find(".home_section"); //here I need to calculate which is the next DIV to scroll to
$('html, body').animate({
scrollTop: next.offset().top
});
});
}
问题是我不知道如何检查哪个是第一个 .home_section
DIV 从顶部开始可见,因此我无法计算要滚动到的下一个目标 DIV。
感谢您的帮助
最佳答案
我将循环遍历所有 .home_sections
div,并像这样获取第一个 :visible
var divs = $(".home_section");
for(var x = 0; x < divs.length; x++){
if($(divs[x]).is(":visible")){
//do what you need here
var me = divs[x];
var next = x < divs.length - 1 ? divs[x] : undefined;
if(next){
//do the scroll
}
//then break the for loop
break;
}
}
这样你就有了一个 div 数组,你找到第一个可见的,然后你就有了对 nth+1
div 的引用。
另一个应该有效的解决方案:
var firstVisible = $(".home_section:visible:eq(0)");
var next = $(firstVisible).next();
希望这有帮助
关于javascript - jQuery 按类名从顶部开始选择 DIV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27228046/