【发布时间】:2015-04-05 23:28:57
【问题描述】:
我尝试将导航菜单与滚动绑定。效果:当我滚动窗口浏览器时,活动菜单项将突出显示。
这是html:
<ul class="navigation">
<li><a href="#intro">HOME</a></li>
<li><a href="#anchor1">Link 1</a></li>
<li><a href="#anchor2">Link 2</a></li>
<li><a href="#anchor3">Link 3</a></li>
<li><a href="#anchor4">Link 4</a></li>
<li><a href="#anchor5">Link 5</a></li>
<li><a href="http://localhost/pages/blog/">BLOG</a></li>
</ul>
jquery 代码是:
$(window).load(function(){
// Cache selectors
var lastId,
topMenu = $(".navigation"),
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");
}
});
此错误出现在 firbug 控制台上:
Error: Syntax error, unrecognized expression: http://localhost/pages/blog/
我发现代码没有处理绝对网址:
var item = $($(this).attr("href"));
然后我将其替换为:
var item = $(this).attr('href').split('=');
现在这个错误已经显示:
TypeError: $(...).offset(...) is undefined
if ($(this).offset().top < fromTop)
注意,当我删除 html 行时:
<li><a href="http://localhost/pages/blog/">BLOG</a></li>
一切顺利。但是有了它,这些错误发生了,菜单滚动效果没有发生。
你有什么线索,问题出在哪里?我该如何解决?
【问题讨论】:
-
你能设置fiddle,和/或提供css和html的其余部分吗?
-
@nevermind 我用的是firebug。。我已经插入了相关的html,剩下的很长,包含很多部分,每个部分都有ID。关于css,它只是改变活动类的颜色。
标签: javascript jquery html menu navigation