根据页面上的位置更改列表项的类别

时间:2013-07-20 11:36:58

标签: javascript jquery

在我的site上,我有一个单页导航菜单。当我点击链接时,页面向下滚动到相应的部分。 我正在使用magicline jquery,它将悬停列表项的类设置为“当前”,以实现移动下划线效果。

但是,当用户查看页面的相应部分时,我还需要将li的类设置为“当前”。我只是做一个点击事件,但当然如果用户没有点击向下滚动,或者之后向上或向下滚动到不同的部分,这将无效。

这是我到目前为止所尝试过的,没有成功。有什么想法吗?

<div class="navbar navbar-fixed-top ogNav">
  <div class="navbar-inner">
    <div class="container-fluid">

      <a class="brand" href="index.php">Kyle Hagler</a>
      <div class="nav-collapse collapse nav-wrap">


        <ul class="nav pull-right" id="topnav">
          <li id="homeLink" class="current"><a id="home" href="javascript:;" class="first">Home</a></li>
          <li id="workLink"><a href="#recent">Work</a></li>
          <li id="aboutLink"><a href="#about">About</a></li>
          <li id="contactLink"><a class="last" href="#contact">Contact</a></li>
        </ul>
      </div><!--/.nav-collapse -->
    </div>
  </div>
</div>


    var recent = $('#recent').offset().top; // Get the position of the recent section
    var about = $('#about').offset().top; // Get the position of the about section
    var contact = $('#contact').offset().top; // Get the position of the contact section

     $(window).scroll(function(){ // Window on scroll
            var scroll = $(window).scrollTop(); // Get the position of the scroll

            if(scroll > recent) {
                $('#topnav li').removeClass();
                $('#workLink').addClass('current'); 
            }

            if(scroll > about) {
                $('#topnav li').removeClass();
                $('#aboutLink').addClass('current');
            }   

            if(scroll > contact) { // if scroll is greater than contact position then modify the menu
                $('#topnav li').removeClass();
                $('#contactLink').addClass('current');
            }
        });

3 个答案:

答案 0 :(得分:1)

你可以像这样轻松地完成

var about = $('#about').offset().top; // Get the position of the about section
var contact = $('#contact').offset().top; // Get the position of the contact section

$(window).scroll(function(){ // Window on scroll
    var scroll = $(window).scrollTop(); // Get the position of the scroll
    if(scroll > contact) { // if scroll is greater than contact position then modify the menu
        // Change menu to contact
    if(scroll > about) {
       // Change menu to about 
    }
});

答案 1 :(得分:0)

看一下Bootstrap Scrollspy http://twitter.github.io/bootstrap/javascript.html#scrollspy,也许你可以找到一些对你有用的脚本。

答案 2 :(得分:0)

也许是一个调整它的setInterval。在该功能中,您将测试您的观看距离最近的点。