scrollspy 效果正常,但突然停止工作。我的意思是当 href 链接像这样 href="#id"时,在滚动单页站点时识别菜单的事件元素。但是当 href 像“/home#id”一样给出时它停止工作。我想像这样使用它。由于该站点使用通用导航。
这是我的代码:
/ 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");
}
});
谁能帮我解决这个问题
这是一个 fiddle
任何帮助都会很棒。提前致谢 !
最佳答案
var cur = scrollItems!=null?scrollItems.map(...):null;
在这行之后 cur 要么是 something 要么是 null。 如果它为 null,则您不能像数组一样对其进行索引,或者就此而言,使用 cur.length 获取其长度。
您没有指定错误,但我敢打赌它说的是“TypeError:cur is null”。 解决方案取决于您实际希望代码执行的操作,但我建议将函数的其余部分包装在
if (cur) {
...
}
关于javascript - Scrollspy 效果停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21526583/