Javascript Scrollspy与jQuery和scrollTo插件
我正试图在我正在开发的网站上实现ScrollSpy 这是我下面教程的链接 下面是演示: 我正试图使他们的脚本适应我的需要,但我一直在javascript上遇到错误,控制台说无法读取未定义的属性“top” 这是我的JavascriptJavascript Scrollspy与jQuery和scrollTo插件,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我正试图在我正在开发的网站上实现ScrollSpy 这是我下面教程的链接 下面是演示: 我正试图使他们的脚本适应我的需要,但我一直在javascript上遇到错误,控制台说无法读取未定义的属性“top” 这是我的Javascript */$(document).ready(function(){ $(".menu li a").click(function(evn){ evn.preventDefault(); $('html,body').scrollTo(this.has
*/$(document).ready(function(){
$(".menu li a").click(function(evn){
evn.preventDefault();
$('html,body').scrollTo(this.hash, this.hash);
});
/**
* This part handles the highlighting functionality.
* We use the scroll functionality again, some array creation and
* manipulation, class adding and class removing, and conditional testing
*/
var aChildren = $(".menu 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(); // 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];
if (theID.length) {
var divPos = $(theID).offset().top;
var divHeight = $(theID).height(); // get the height of the div in question
if (windowPos >= divPos && windowPos < (divPos + divHeight)) {
$("a[href='" + theID + "']").parent().addClass("active");
} else {
$("a[href='" + theID + "']").parent().removeClass("active");
}
}
}
if(windowPos + windowHeight == docHeight) {
if (!$(".menu li:last-child a").hasClass("active")) {
var navActiveCurrent = $(".active").attr("href");
$("a[href='" + navActiveCurrent + "']").removeClass("active");
$(".menu li:last-child a").addClass("active");
}
}
}); });
这是我正在开发的网站
有人能帮我吗?问题是您正在使用href作为jQuery的选择器。您需要形成正确的选择器:
for (var i=0; i < aArray.length; i++) {
var theID = aArray[i];
if (theID.length) {
var divPos = $(theID).offset().top;
var divHeight = $(theID).height(); // get the height of the div in question
if (windowPos >= divPos && windowPos < (divPos + divHeight)) {
$("a[href='" + theID + "']").parent().addClass("active");
} else {
$("a[href='" + theID + "']").parent().removeClass("active");
}
}
}
应改为:
for (var i=0; i < aArray.length; i++) {
var theID = aArray[i];
var selector = "a[href='" + theID + "']";
if (theID.length) {
var divPos = $(selector).offset().top;
var divHeight = $(selector).height(); // get the height of the div in question
if (windowPos >= divPos && windowPos < (divPos + divHeight)) {
$(selector).parent().addClass("active");
} else {
$(selector).parent().removeClass("active");
}
}
}
它解决了你发布的问题吗?您没有提到突出显示,只是列出了javascript控制台错误。如果它解决了这个问题,请接受答案并打开一个新的带有突出显示的特定问题。谢谢