jquery - 更改页面滚动上的事件菜单项?

标签 jquery html

当您向下滚动页面时,事件菜单项会发生变化。这是怎么做到的?

最佳答案

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/

相关文章:

javascript - 为什么函数不等待另一个函数

javascript - 提交表单后删除输入字段的值属性中设置的值

javascript - 使用 Javascript 加载下拉值

javascript - 防止点击暂停视频

jquery - 使用 jquery 将类添加到 nth-child

javascript - HTML5 Canvas JavaScript 十字线网格

css - HTML5 视频在 native 全屏模式下不会最大化超出容器尺寸

javascript - 用Jquery限制div的上下移动

javascript - 在 jQuery 中使用动态参数和值更改 URL 的查询参数

html - 将图像放置在位于顶部中心的 div 后面