链接到同一页面上的ID时滚动

时间:2014-10-15 08:52:19

标签: javascript jquery html css twitter-bootstrap

注意:我是webdev的新手,我正在使用bootstrap构建此站点

我正在建立一个单页网站,顶部的导航栏会将用户指向相关的ID。我遇到的问题是我希望它在点击时滚动到id(参见http://www.blastprocessor.co.uk/)。我还想在用户滚过特定ID时将该类设置为活动状态。

我不知道从哪里开始,但我会在这里发布我的HTML代码。

<nav class="navbar navbar-default" data-spy="affix" data-offset-top="34">
<div class="container">
<div class="navbar-collapse collapse navbar-responsive-collapse" id="main-menu">
<ul class="nav navbar-nav">
<li class="active"><a href="#whatissm">What We Are</a></li>
<li class=""><a href="#whyusesm">Why Us</a></li>
<li class=""><a href="#whatdoessmeoffer">What We Offer</a></li>
<li class=""><a href="#contactus">Contact Us</a></li>
</ul>
<ul class="nav navbar-nav pull-right">
<li><a href="#">Right Link</a></li>
</ul>
</div>
</div>
</nav>

2 个答案:

答案 0 :(得分:0)

使用JQuery:

请参阅here滚动并动画显示您的ID。

要在滚动ID之后添加课程,请使用:

//assign the window and all the contents into variables
//instead of going and grabbing it from the DOM on every scroll

var $window = $(window),
    $content = $('.content');

$window.scroll(function () {
    $content.each(function () {
        //for each element that has a class of content
        //check its position and add SomeClass
        if ($window.scrollTop() >= $(this).position().top) {
            $(this).addClass('SomeClass');
        } else if ($window.scrollTop() <= $(this).position().top) {
            //if window position is less then remove it
            $(this).removeClass('SomeClass');
        }
    });
});

答案 1 :(得分:0)

您可以使用以下功能制作滚动动画。关于添加课程&#39; active&#39;实际上你可以按照@ahb的回答来过去的id。根据您的需要,我只在函数中添加了一个var reduce,它将帮助您从实际偏移中减少50px

$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
  var reduce = 50;
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top - reduce
        }, 1000);
        return false;
      }
    }
  });
});

ORIGINAL SOURCE

DEMO

相关问题