当您向下滚动页面时,事件菜单项会发生变化。这是怎么做到的?
最佳答案
由 binding to the scroll event 完成容器(通常是窗口)。
简单示例:
// 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");
});
见上in action at jsFiddle包括滚动动画。
关于jquery - 更改页面滚动上的事件菜单项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9979827/