【发布时间】:2014-02-03 11:47:11
【问题描述】:
scrollspy 效果很好,但突然停止工作。我的意思是在滚动单页站点时识别菜单的活动元素,当href链接给出这样的href =“#id”时。但是当像“/home#id”一样给出href时它会停止工作。我想像这样使用它。由于该网站使用通用导航。
这是我的代码:
/ Cache selectors
var lastId,
topMenu = $("#timenav"),
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 click handler to menu items
// so we can get a fancy scroll animation
menuItems.click(function(e){
var href = $(this).attr("href"),
offsetTop = href === "#" ? 0 : $(href).offset().top-topMenuHeight+1;
$('html, body').stop().animate({
scrollTop: offsetTop
}, 300);
e.preventDefault();
});
// 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");
}
});
谁能帮我解决这个问题
这是一个小提琴
任何帮助都会很棒。提前致谢 !
【问题讨论】:
-
这还是不行吗?除非我遗漏了什么,否则我在 Chrome 中似乎可以正常工作
-
@dcodesmith 没有“/home”也能正常工作。我们需要 /home 用于导航目的
-
"http://www.drkeenly.com/home"和"http://www.drkeenly.com"不是给你相同的页面吗? -
@dcodesmith 是的,导航在整个站点中都很常见。所以我们需要“/home”。
-
@franchez 很抱歉它是一个测试服务器
标签: javascript jquery html navigation scroll