更改页面滚动上的活动菜单项? [英] Change Active Menu Item on Page Scroll?
本文介绍了更改页面滚动上的活动菜单项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这个功能的一个很好的例子可以在这里看到: http://www.maddim.com/demos/spark -r6 /
A good example of this feature would be seen here: http://www.maddim.com/demos/spark-r6/
向下滚动页面时,活动菜单项会发生变化。这是怎么做到的?
As you scroll down the page, the active menu item changes. How is this done?
推荐答案
这是由绑定到容器的滚动事件(通常是窗口)。
It's done by binding to the scroll event of the container (usually window).
快速举例:
// Cache selectors
var topMenu = $("#top-menu"),
topMenuHeight = topMenu.outerHeight()+15,
// All list items
menuItems = topMenu.find("a"),
// Anchors corresponding to menu items
scrollItems = menuItems.map(function(){
var item = $($(this).attr("href"));
if (item.length) { return item; }
});
// Bind to scroll
$(window).scroll(function(){
// Get container scroll position
var fromTop = $(this).scrollTop()+topMenuHeight;
// Get id of current scroll item
var cur = scrollItems.map(function(){
if ($(this).offset().top < fromTop)
return this;
});
// Get the id of the current element
cur = cur[cur.length-1];
var id = cur && cur.length ? cur[0].id : "";
// Set/remove active class
menuItems
.parent().removeClass("active")
.end().filter("[href='#"+id+"']").parent().addClass("active");
});
见上文在jsFiddle中行动,包括滚动动画。
See the above in action at jsFiddle including scroll animation.
这篇关于更改页面滚动上的活动菜单项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文