繁体   English   中英

在页面滚动中,将活动类添加到<a href>固定菜单中的</a>匹配<a href>哈希</a>

[英]On page scroll add active class to matching <a href>hash in fixed menu

这个人已经花了我一些时间来弄清楚,所以我呼吁有人来改善我的生活。

如果您的菜单链接仅包含#hashlocation,那么这段流行的代码非常有用-当您浏览页面的那部分时,它将使用活动类更新菜单项。

// 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");
});​

对我来说问题是,如果我的菜单包含非哈希标签的其他页面,则显然不起作用,尤其是那些带有哈希标签的页面,它们之前都带有完整的URL

我需要调整此代码,以便它不会引发“语法错误,无法识别的表达式”,并且还接受菜单可能包含指向其他位置的其他链接这一事实。

这是一个小提琴http://jsfiddle.net/stevenmunro/ytbhrz1g/2/

如果您要从“ Foo”中删除哈希之前的完整URL,它将起作用。

我努力了

menuItems = topMenu.find('a[href*=#]'),

以及在scrollItems = menuItems.map中

var item = $($(this).attr("href").split("#"));
item = $("#" + item[1]);

参考文献

更改页面滚动上的活动菜单项?

感谢您的帮助。

感谢James Hay使我走上正确的道路。 该建议与我已经尝试过的建议非常相似,但是现在它是单线的,并且效果很好。

我也改变了;

menuItems = topMenu.find("a"),

menuItems = topMenu.find('a[href*=#]'),

并且改变了;

menuItems
 .parent().removeClass("active")
 .end().filter("[href=#"+id+"]").parent().addClass("active");

menuItems
 .parent().removeClass("active")
 .end().filter("[href$=" + id + "]").parent().addClass("active");

只要菜单中的项目以及它们在页面中的顺序过高,就可以使用。 如果菜单项被加扰,则不会按预期更改。 也许这也是我们可以解决的其他问题,但问题已得到解答,非常感谢。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM