2013-11-21 43 views
2

我对JavaScript非常陌生,所以我提前致歉。我正在尝试使用导航链接列表为学校项目创建一个页面的html文档,该链接列表在锚点滚动时发生更改。我试过了Jfiddle和通过stackoverflow找到的各种不同的方法。这就是我现在想的方法:http://jsfiddle.net/m2zQE/滚动不起作用的jQuery高光导航链接

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

我用html5boilerplate作为起始point.Thank你提前。

+2

它的工作,你想 – mehdi

+0

@mehdi解释一下?我根本没有看到它的工作。顶部链接是他们正在尝试使用的内容,底部网址是他们尝试使用它的网站。在网站上我没有看到它的工作。 – Ruddy

+0

是的,底部链接是我试图使用它的。我无法使它工作,并且我没有在JavaScript控制台中发现任何错误。我不确定它是否将我的jQuery代码放在HTML文档中,或者我完全错过了某些东西。也许有更简单的方法来实现这个功能? –

回答

0

没有太多的时间来研究你的代码,但是当我输入行

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

到开发工具的控制台,它都将返回NaN。

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

我建议你给每个元素的ID和尝试:

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

,或者如果你坚持不给ID,

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

但是请注意,这是不工作在所有浏览器作为第n -child选择器是一个CSS3选择器。或者,如果你知道如何正确使用他人的工作,你可以尝试使用bootstrap 3.0,其中已经有一个名为scrollspy的函数,它可以完成你正在做的事情。

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

+0

谢谢,我会给bootstrap一个尝试,似乎是我最好的选择,因为它正在做我想要的,包括手风琴的效果。感谢您的帮助。 –