我收到了类似" Uncaught TypeError:无法读取属性' top'未定义" ...我不知道修复的方法!! ..任何人都可以告诉我答案!!! .. var divPos = $(theID).offset()。顶部;
var aChildren = $("nav li").children(); // find the a children of the list items
var aArray = []; // create the empty aArray
for (var i=0; i < aChildren.length; i++) {
var aChild = aChildren[i];
var ahref = $(aChild).attr('href');
aArray.push(ahref);
} // this for loop fills the aArray with attribute href values
$(window).scroll(function(){
var windowPos = $(window).scrollTop()+85; // get the offset of the window from the top of page
var windowHeight = $(window).height(); // get the height of the window
var docHeight = $(document).height();
for (var i=0; i < aArray.length; i++) {
var theID = aArray[i];
var divPos = $(theID).offset().top;// get the offset of the div from the top of page.... error occured here!!!
var divHeight = $(theID).height(); // get the height of the div in question
if (windowPos >= divPos && windowPos < (divPos + divHeight)) {
$("a[href='" + theID + "']").addClass("active");
} else {
$("a[href='" + theID + "']").removeClass("active");
}
}
if(windowPos + windowHeight == docHeight) {
if (!$("nav li:last-child a").hasClass("active")) {
var navActiveCurrent = $(".active").attr("href");
$("a[href='" + navActiveCurrent + "']").removeClass("active");
$("nav li:last-child a").addClass("active");
}
}
});
答案 0 :(得分:3)
我刚刚改变了
var divPos = $(theID).offset().top;
到
var divPosid = $(theID);
if (!divPosid.length) {
return;
}
var divPos = divPosid.offset().top; // get the offset of the div from the top of page
答案 1 :(得分:0)
把
console.log(theID);
var divPos = $(theID).offset().top;
你会得到答案。