当目标处于顶部滚动状态时,如何从菜单中激活项目



我正在改进一个小网站,其中有一个菜单固定在窗口的任何位置,当此链接的ID在窗口中时,您应该激活该项目。

为了开始了解它是如何工作的,我做了这个小提琴 http://jsfiddle.net/kanzer/ydwzwa49/1/这很好用,这就是我想要的。

这对我的以下代码有很大帮助:

// Cache selectors
var lastId,
    topMenu = $("#prime-menu-slide"),
    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 : "";
   if (lastId !== id) {
       lastId = id;
       // Set/remove active class
       menuItems
         .parent().removeClass("active")
         .end().filter("[href=#"+id+"]").parent().addClass("active");
   }                   
});

但是在现实生活中,在我想放的网站上它不起作用,我无法理解,为什么?留下不起作用的小提琴。

http://jsfiddle.net/kanzer/ev6xn7rc/2/

谢谢你的帮助!! :)

看起来你的代码不喜欢这种链接:

<a href="#" class="fp_comment_click">Commentaires</a>

这是因为这段代码:

scrollItems = menuItems.map(function(){
      var item = $($(this).attr("href"));

代码没问题,但如果href="#"var item = $("#")-->错误,js 就会死亡。

将其替换为以下内容(您必须找出正确的锚点):

<a href="#historique-et-anecdotes" class="fp_comment_click">Commentaires</a>

。它应该有效。或者修改提到的代码,记住我提到的细节。

希望对您有所帮助。

最新更新