如何在引导程序中使用平滑滚动仍然在导航栏中的页面外部有一个链接

时间:2015-12-14 14:19:18

标签: jquery css twitter-bootstrap smooth-scrolling

我使用w3School的教程创建了一个简单的公司单页网站: http://www.w3schools.com/bootstrap/bootstrap_theme_company.asp

一切正常,直到我尝试在导航栏中添加页面外的链接:`

<!-- NAVBAR -->
    <nav class="navbar navbar-default navbar-fixed-top">
  <div class="container">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span> 
      </button>
    </div>
    <div class="collapse navbar-collapse" id="myNavbar">
      <ul class="nav navbar-nav navbar-right">
        <li><a href="#about">ABOUT</a></li>
        <li><a href="#services">SERVICES</a></li>
        <li><a href="#portfolio">PORTFOLIO</a></li>
        <li><a href="#contact">CONTACT</a></li>
        <li><a href="http://www.twitter.com/mytwitter">@mytwitter</a></li>
      </ul>
    </div>
  </div>
</nav>`

twitter链接无法打开,但如果我删除了平滑的滚动脚本,则无效:

<script>
$(document).ready(function(){
  // Add smooth scrolling to all links in navbar + footer link
  $(".navbar a, footer a[href='#myPage']").on('click', function(event) {

  // Prevent default anchor click behavior
  event.preventDefault();

  // Store hash
  var hash = this.hash;

  // Using jQuery's animate() method to add smooth page scroll
  // The optional number (900) specifies the number of milliseconds it takes to scroll to the specified area
  $('html, body').animate({
    scrollTop: $(hash).offset().top
  }, 900, function(){

    // Add hash (#) to URL when done scrolling (default click behavior)
    window.location.hash = hash;
    });
  });
})
</script>

有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:1)

尝试将特定类应用于“平滑滚动”元素

    <li><a class="scroll" href="#about">ABOUT</a></li>

与页脚链接相同

然后

$(".scroll").on('click', function(event) {