我试图在我的网站上实现此功能,以便滚动到相应的部分时导航样式会发生变化。
http://stanhub.com/sticky-header-change-navigation-active-class-on-page-scroll-with-jquery/
我能看到的唯一区别是我创建的导航在到达页面顶部后变得粘滞。
当我投入
时console.log(refElement.position())
我明白了
Object {top: 716.984375, left: 50.5}
Object {top: 1811.796875, left: 50.5}
我收到错误
"Uncaught TypeError: Cannot read property 'top' of undefined" on from function.
在这一行:
if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
这是脚本
$(document).ready(function() {
$(document).on("scroll", onScroll);
function onScroll(event){
var scrollPos = $(document).scrollTop();
$('.cn17w1.original a').each(function () {
var currLink = $(this);
var refElement = $(currLink.attr("href"));
if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
$('.cn17w1.original ul li a').removeClass("active");
currLink.addClass("active");
}
else{
currLink.removeClass("active");
}
});
}
});
答案 0 :(得分:0)
var refElement = $(currLink.attr("href"));
这将返回一个空的jQuery集,当调用position()时,它将返回undefined。原因$(currLink.attr("href"))
未选择DOM元素,它选择任意文本,特别是href
元素的currLink
属性值。