当目标位于顶部滚动时,如何从菜单激活项目?

时间:2015-01-09 21:09:28

标签: javascript jquery html dom

我正在改进一个小网站,在窗口的任何位置都有固定的菜单,你应该在窗口中链接的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/

谢谢你的帮助!!! :)

1 个答案:

答案 0 :(得分:1)

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

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

这是因为这段代码:

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

代码还可以,但如果href="#"var item = $("#") - &gt;错误,js死了。

将其替换为类似的东西(你必须弄清楚正确的锚):

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

......它应该work。或者修改上面提到的代码,记住我提到的细节。

希望它有所帮助。