jQuery高亮显示滚动导航链接不起作用

jQuery Highlight Nav links on scroll not working

本文关键字:链接 不起作用 导航 滚动 高亮 显示 jQuery      更新时间:2023-09-26

我对JavaScript非常陌生,所以我提前道歉。我正试图为一个学校项目创建一个一页的html文档,使用一个链接列表进行导航,当锚滚动到时,这些链接会发生变化。我尝试了Jfiddle和stackoverflow上的各种不同方法。这是我现在尝试的方法:http://jsfiddle.net/m2zQE/

 var topRange = 200, // measure from the top of the viewport to X pixels down
 edgeMargin = 20, // margin above the top or margin from the end of the page
 animationTime = 1200, // time in milliseconds
 contentTop = [];

$(document).ready(function () {
     // Stop animated scroll if the user does something
     $('html,body').bind('scroll mousedown DOMMouseScroll mousewheel keyup', function (e) {
         if (e.which > 0 || e.type == 'mousedown' || e.type == 'mousewheel') {
             $('html,body').stop();
         }
     });
     // Set up content an array of locations
     $('#nav').find('a').each(function () {
         contentTop.push($($(this).attr('href')).offset().top);
     });
     // Animate menu scroll to content
     $('#nav').find('a').click(function () {
         var sel = this,
             newTop = Math.min(contentTop[$('#nav a').index($(this))], $(document).height() - $(window).height()); // get content top or top position if at the document bottom
         $('html,body').stop().animate({
             'scrollTop': newTop
         }, animationTime, function () {
             window.location.hash = $(sel).attr('href');
         });
         return false;
     });
     // adjust side menu
     $(window).scroll(function () {
         var winTop = $(window).scrollTop(),
             bodyHt = $(document).height(),
             vpHt = $(window).height() + edgeMargin; // viewport height + margin
         $.each(contentTop, function (i, loc) {
             if ((loc > winTop - edgeMargin && (loc < winTop + topRange || (winTop + vpHt) >= bodyHt))) {
                 $('#nav li')
                     .removeClass('selected')
                     .eq(i).addClass('selected');
             }
         });
     });
     });

我仍然没有任何运气。我已经搜索过是否可以调试这个问题,并尝试更改代码的顺序以及调用jquery的顺序。

以下是该网站的链接:https://googledrive.com/host/0BwvPQbnPrz_LMlZDeGlFY2Yydmc/index.html

我用html5油背板作为起点。提前谢谢。

没有太多时间查看代码,但当我输入行时

Math.min(contentTop[$('#nav a').index($(this))], $(document).height() - $(window).height())

进入开发人员工具的控制台,返回NaN。

所以我想问题是你没有正确设置你的scrollTop。

我建议你给每个元素一个id,然后尝试:

$('html, body').animate({
    scrollTop: $("#elementID").offset().top
}, 2000);

或者如果你坚持不提供身份证,

$('html, body').animate({
    scrollTop: $("#container-fulid:nth-child(2)").offset().top
}, 2000);

但请注意,这并不是在所有浏览器上都有效,因为第n个子选择器是CSS3选择器。

或者,如果你知道如何正确使用他人的工作,你可以尝试使用bootstrap 3.0,其中已经包含了一个名为scrollspy的函数,它可以做你正在做的事情。

http://getbootstrap.com/javascript/#scrollspy