jQuery 使用下一个/上一个按钮滚动到下一个 div 类
我想要的是固定导航,使用 NEXT 和 PREV 按钮基本上将页面滚动到具有section"类的下一个 div.
What I'd like is for the fixed navigation, with NEXT and PREV buttons to basically scroll the page to the next div with the class of "section".
我已经设置 jQuery 实质上为 NEXT 和 PREV href 添加了一个点击功能.然后这个点击函数将使用 ScrollTop 移动到具有 .section 类的下一个 duv.
I've setup jQuery to essentially add a click function to the NEXT and PREV hrefs. This click function will then use ScrollTop to move to the next duv with a class of .section.
这里是 jQuery:
Here is the jQuery:
$('div.section').first();
// binds a click event-handler to a elements whose class='display'
$('a.display').on('click', function(e) {
// prevents the default action of the link
e.preventDefault();
// assigns the text of the clicked-link to a variable for comparison purposes
var t = $(this).text(),
that = $(this);
console.log(that.next())
// checks if it was the 'next' link, and ensures there's a div to show after the currently-shown one
if (t === 'next' && that.next('div.section').length > 0) {
//Scroll Function
$('html, body').animate({scrollTop:that.next('div.section').scrollTop()});
}
// exactly the same as above, but checking that it's the 'prev' link
else if (t === 'prev' && that.prev('div.section').length > 0) {
//Scroll Function
$('html, body').animate({scrollTop:that.prev('div.section').scrollTop()});
}
});
我目前正在使用带有大量评论的 jQuery 开发 JSfiddle,以帮助您消化:http://jsfiddle.net/ADsKH/1/
I am currently working on JSfiddle with heavily commented jQuery to help you digest: http://jsfiddle.net/ADsKH/1/
我有一个 console.log 目前正在检查 (that.next()) 以确定下一个 .section 将是什么,但它给了我一些非常奇怪的结果.
I have a console.log currently checking for (that.next()) to determine what the next .section will be, but it's giving me back some very weird results.
为什么这没有按预期工作?
Why this isn't working as intended?
推荐答案
你的 that
找不到 .next('.section')
因为它嵌套在里面.navigation
.
Your that
can't find a .next('.section')
because it's nested inside .navigation
.
来自 .next()
的 jQuery 文档.
From the jQuery documentation for .next()
.
获取匹配元素集中每个元素的紧随其后的兄弟.
Get the immediately following sibling of each element in the set of matched elements.
这是一个基于您的代码的工作示例
相关文章