【发布时间】:2018-09-19 20:39:29
【问题描述】:
我试图通过添加活动类来突出显示页面滚动上的导航。
这是我的脚本(我从这里得到https://codepen.io/joxmar/pen/NqqMEg):
// Cache selectors
var lastId,
topMenu = $("#mainNav"),
topMenuHeight = topMenu.outerHeight()+1,
// 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
}, 850);
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");
}
});
我在控制台中收到以下错误: 未捕获的错误:语法错误,无法识别的表达式:[href=#]
我正在使用 jquery-3.3.1.min.js
编辑:更新 - 我不再收到错误,但它不起作用。我在变量 formTop 上做一个控制台日志,我得到的是 NaN
【问题讨论】:
-
我在你的 codepen 中没有收到错误
-
@VVV 导致使用 jquery 2.1.3 的 codepen。更改为 3.3.1
标签: javascript jquery