滚动到下一个元素
我正在努力解决jquery或javascript问题。
它已经很烦人,告诉我在这个问题上我可能觉得太复杂了。
所以我的标记(简称)看起来像这样:
My Content scroll down My Content scroll down My Content scroll down My Content scroll down
基本上只是一些容器。
每个包含不同的内容和按钮。
计划:
1)单击按钮后,窗口应向下滚动到下一个容器 。
2)最后一个按钮再次滚动到第一个容器。 所以我需要一个循环 。
3)容器的数量可能会因页面而异。
编辑: 4)容器可能并不总是彼此直接兄弟姐妹(见下面的标记)
问题:
我可以通过为每个容器提供一个唯一的ID作为滚动效果的目标来实现这一点。
问题在于它很快就会变得太乱。
不能我只是以某种方式将“ 下一个对象与类:容器 ”作为目标,然后滚动到那个?
我不确定js或jquery是否是正确的方法。 我对两者的了解有限。
我真的很感激能朝着正确的方向前进。
编辑:容器可能并不总是彼此的直接兄弟姐妹。
My Content scroll down My Content scroll down My Content scroll down My Content scroll down My Content scroll down My Content scroll down
简单解决方案
要获取下一个容器,请尝试使用next()
。
基本上,
容器是彼此的兄弟,所以在一个div容器上调用.next()
会给你下一个。
$(".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 });
你只需使用$(this)
获取链接对象, .parent()
获取链接的父级,即
,然后使用.next()
获取下一个兄弟(注意它会自动换行,所以最后一个
之后的兄弟是第一个
,。offset() 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 = container.nextAll('.container, :has(.container)').first();
。
最后,如果找不到任何内容,请通过nextdiv.length==0
进行检查,只需抓住整个页面中的第一个.container
。
然后滚动到任何.container
被抓住了。
要为滚动设置动画,请将scrollTop
属性放在animate
函数中:
// $(document).scrollTop(nextdiv.offset().top); // snaps to new scroll position $('body').animate({scrollTop:nextdiv.offset().top},300); // animates scrolling
这不需要JavaScript。 您可以使用HTML锚点。
My Content scroll down My Content scroll down My Content scroll down My Content scroll down
你想要的东西可以通过parent()
和child()
轻松实现。
如果每个页面上的容器数量不同,那么您应该按顺序开始ID(不知道这是一个术语)容器。 类似于, class="container-1"
最后一个按钮上的click事件应该是这样的:
var num = $('div[class^="container-"]').filter(function() { return((" " + this.className + " ").match(/\scontainer-\d+\s/) != null); }); num++; var last_container = $(this).parent('.container' + num); last_container .scrollTo();
我相信你可以弄清楚下一个按钮应该做什么;)