【问题标题】:How to change the active class on scroll in bootstrap using jquery?如何使用 jquery 在引导程序中滚动时更改活动类?
【发布时间】:2017-01-13 08:26:00
【问题描述】:

它是一个登陆页面,因此所有导航链接都代表同一页面上的一个部分。

我的导航栏

 <nav class="navbar navbar-default navbar-fixed-top">
        <div class="container-fluid">
          <!-- Brand and toggle get grouped for better mobile display -->
          <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
              <span class="sr-only">Toggle navigation</span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">Brand Name</a>
          </div>

          <!-- Collect the nav links, forms, and other content for toggling -->
          <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">            
            <ul class="nav navbar-nav navbar-right">
              <li class="active"><a href="#home">Home</a></li>  
              <li><a href="#about">About Us</a></li> 
              <li><a href="#choose">Why This Company</a></li> 
              <li><a href="#mission">Mission and Vision</a></li> 
              <li><a href="#services">Services</a></li> 
              <li><a href="#">How it Works</a></li> 
              <li><a href="#destination">Destination</a></li> 
              <li><a href="#associate">Associate Partners</a></li>             
              <li><a href="#contact">Contact Us</a></li> 
            </ul>
          </div><!-- /.navbar-collapse -->
        </div><!-- /.container-fluid -->
      </nav>

点击它使用 jquery 更改活动类

        $(document).ready(function () {
    $('.nav li a').click(function(e) {

        $('.nav li').removeClass('active');

        var $parent = $(this).parent();
        if (!$parent.hasClass('active')) {
            $parent.addClass('active');
        }
    });
});

我无法在滚动时执行此操作。每个导航链接代表同一页面上的一个部分。

谢谢。

【问题讨论】:

  • 使用jQuery滚动事件,api.jquery.com/scroll
  • 点击处理程序与滚动事件有什么关系?你能详细说明你的问题吗

标签: jquery


【解决方案1】:
<div id="about"></div>
...

 $(window).on('scroll', function(event){
   var scrollPos = $(document).scrollTop();
   $(".nav li a").each(function () {
     var currLink = $(this);
     var refElement = $(currLink.attr("href"));

     if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
       currLink.parent().addClass("active").siblings().removeClass("active"); 
       return;
     }
     else{
       currLink.parent().removeClass("active");
     }
   })
 })

【讨论】:

  • 我问的是滚动而不是点击。我已经在我的问题中给出了点击的答案。
猜你喜欢
  • 1970-01-01
  • 2013-08-01
  • 2013-08-17
  • 2015-10-02
  • 2012-12-19
  • 1970-01-01
  • 2016-03-25
  • 1970-01-01
  • 2017-06-27
相关资源
最近更新 更多