CSS 类取决于页面位置
我在页面顶部有一个固定导航,其中包含可通过 jQuery 平滑滚动到页面不同部分 (ID) 的链接。
是否有任何可能的方法可以根据您所在页面的哪个部分将 css 类(例如 .current)附加到导航链接?
例如,当我单击“关于”时,它会向下滚动到“关于”部分,并且只要您停留在该部分,导航文本也会变为橙色?
我不久前在某个地方看到过这种做法,但我不记得那个网站,甚至不记得如何描述这种行为来搜索它。
编辑:这是与我正在寻找的内容类似的链接: http://www.fat-man-collective.com/hello.php
图标会根据您在页面上的位置而变化。
脚本:
<script>
function goToByScroll(id){
$('html,body').animate({scrollTop: $("#"+id).offset().top - 50},'500');
}
</script>
HTML:
<a href="javascript:void(0)" onClick="goToByScroll('about')">About</a>
[...]
<div id="about">
[...]
</div>
非常感谢任何帮助。
I have a fixed navigation at the top of the page that has links that smoothly scroll you around to different sections (IDs) of the page via jQuery.
Would there be any possible way to have a css class (e.g. .current) appended to the navigation links depending on what section of the page you're at?
For example, when I click "About", it'll scroll down to the About section and also make the navigation text orange as long as you stay in that section?
I've seen this done somewhere a while ago but I don't remember the website or even how to describe this behavior to search for it.
EDIT: Here's a link to something siliar to what I'm looking for:
http://www.fat-man-collective.com/hello.php
The icons change depending on your position on the page.
Script:
<script>
function goToByScroll(id){
$('html,body').animate({scrollTop: $("#"+id).offset().top - 50},'500');
}
</script>
HTML:
<a href="javascript:void(0)" onClick="goToByScroll('about')">About</a>
[...]
<div id="about">
[...]
</div>
Any help is greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
通过检查所需元素的 offset()* 函数,然后进行相应的响应编码,可以实现这一点。您可以跟踪元素的偏移量,并根据生成的偏移量,相应地应用或删除适当的类。
*请参阅 offset() 的文档
This would be possible by examing the
offset()
* function of the desired element and then coding to respond accordingly. You can track the offset of an element, and depending on the resulting offset, you would apply or remove the appropriate classes accordingly.*See the documentation for offset()
当您单击导航中的某个部分时,只需修改该类,以便样式成为您想要的样式。
其次,您需要在
scroll
事件上添加一个事件处理程序,该事件处理程序类似地修改导航的类。When you click on a section in the navigation, just modify the class so that the style is what you want it to be.
Secondly, you'll need to add an event handler on the
scroll
event that similar modifies the nav's class.试试这个:
Try this:
四年后......对于那些有同样问题的人,因为希望OP现在已经解决了他的问题。
查看 Bootstrap 的 ScrollSpy 插件,该插件“用于根据滚动位置自动更新导航目标”。有关使用 ScrollSpy 插件的示例,请参阅此详细教程,了解如何制作浮动的、更新的导航栏(就像 Bootstrap 网站使用的那样)。
Four years later...for those that have the same question since hopefully the OP has solved his problem by now.
Check out Bootstrap's ScrollSpy plugin, which "is for automatically updating nav targets based on scroll position." For an example of using the ScrollSpy plugin see this detailed tutorial on how to make a floating, updating navbar (like the Bootstrap site uses).