javascript jQuery 使用下一个/上一个按钮滚动到下一个 Div 类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15125703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery Scroll to Next Div Class with Next / Previous Button
提问by richie
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".
我想要的是固定导航,使用 NEXT 和 PREV 按钮基本上将页面滚动到具有“部分”类的下一个 div。
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 来为 NEXT 和 PREV href 添加一个点击函数。然后,此单击函数将使用 ScrollTop 移动到具有 .section 类的下一个 duv。
Here is the jQuery:
这是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()});
}
});
I am currently working on JSfiddle with heavily commented jQuery to help you digest: http://jsfiddle.net/ADsKH/1/
我目前正在 JSfiddle 上使用大量评论的 jQuery 来帮助您消化:http: //jsfiddle.net/ADsKH/1/
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.
我有一个 console.log 当前正在检查 (that.next()) 以确定下一个 .section 将是什么,但它给了我一些非常奇怪的结果。
Why this isn't working as intended?
为什么这不能按预期工作?
回答by pdoherty926
Your that
can't find a .next('.section')
because it's nested inside .navigation
.
您that
找不到 a.next('.section')
因为它嵌套在.navigation
.
From the jQuery documentation for .next()
.
来自 jQuery 文档.next()
。
Get the immediately following sibling of each element in the set of matched elements.
获取匹配元素集中每个元素的紧随其后的兄弟元素。