简单的解决方案:
要获取下一个容器,请尝试使用next() http://api.jquery.com/next/.
基本上,<div>
容器是彼此的兄弟,所以调用.next()
在一个 div 容器上将为您提供下一个。
$(".button").on("click", function(e) {
$(document).scrollTop($(this).parent().next().offset().top);
// $(this).parent().next() // this is the next div container.
return false; // prevent anchor
});
http://jsfiddle.net/Pm3cj/1/ http://jsfiddle.net/Pm3cj/1/
你只需使用$(this)
获取链接对象,.parent()
获取链接的父级,即<div>
, then .next()
获取下一个同级(注意它会自动换行,因此最后一个之后的同级<div>
is the first <div>!),
。抵消()to get its position relative to the page,
.top` 使其相对于上边框。
然后你只需使用$(document).scrollTop()
滚动到该位置。
对于完全通用的解决方案,请使用:
$(".button").on("click", function(e) {
container = $(this).parent();
// if I am the last .container in my group...
while ( document != container[0] // not reached root
&& container.find('~.container, ~:has(.container)').length == 0)
container = container.parent(); // search siblings of parent instead
nextdiv = container.nextAll('.container, :has(.container)').first();
// no next .container found, go back to first container
if (nextdiv.length==0) nextdiv = $(document).find('.container:first');
$(document).scrollTop(nextdiv.offset().top);
// $(this).parent().next() // this is the next div container.
return false;
});
代码基本使用了container.find('~.container, ~:has(.container)')
找到任何有或正在的兄弟姐妹.container
。如果没有,则沿 DOM 树向上 1 步。
当它发现某个东西是或有一个.container
,它抓住它nextdiv = container.nextAll('.container, :has(.container)').first();
.
最后,如果没有发现任何问题,则检查nextdiv.length==0
,只需抓住第一个.container
在整个页面中。
然后滚动到任何内容.container
被抓住了。
http://jsfiddle.net/Pm3cj/3/ http://jsfiddle.net/Pm3cj/3/
要使滚动动画化,请将scrollTop
财产在animate
功能:
// $(document).scrollTop(nextdiv.offset().top); // snaps to new scroll position
$('body').animate({scrollTop:nextdiv.offset().top},300); // animates scrolling
http://jsfiddle.net/Pm3cj/4/ http://jsfiddle.net/Pm3cj/4/