我正在改进一个小型网站,其中有一个菜单固定在窗口的任何位置,当此链接的 ID 在窗口中时,您应该激活该项目。
为了开始了解它是如何工作的,我制作了这个 fiddle 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");
}
});
但在现实生活中,在我想放置的网站上它不起作用,我无法理解,为什么? 留下不起作用的 fiddle 。
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 就会死掉。
将其替换为类似的内容(您必须找出正确的 anchor ):
<a href="#historique-et-anecdotes" class="fp_comment_click">Commentaires</a>
...应该work 。或者修改提到的代码,记住我提到的细节。
希望有帮助。
关于javascript - 当目标位于顶部滚动时,如何激活菜单中的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27869258/