jQuery - 平滑的滚动代码无法正常工作

时间:2016-06-10 10:03:36

标签: jquery html scroll

所以,我正在创建一个网页,并希望使用jQuery在其中包含一些平滑的滚动。问题是我的代码不起作用,当我点击链接时,页面直接跳转到现场而不是顺利滚动。这是代码的相关部分 -

HTML -

<script src="scroll.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
</head>
<body>
<div id="sec1">
    <span id="header">Heading</span>
    <!--<span id="notheader">Umesh meena is the coolest</span>-->
    <!--<div id="navbar" class="before">lol</div>-->
    <a href="#sec2" id="button1" >link to the page</a>
</div>
<div id="sec2">
    <span id="main">lorem</span>
</div>
</body>
</html>

SCROLL.js文件 -

$(document).ready(function(){
  $('a[href^="#"]').on('click',function (e) {
      e.preventDefault();

      var target = this.hash;
      var $target = $(target);

      $('html, body').stop().animate({
          'scrollTop': $target.offset().top
      }, 900, 'swing', function () {
          window.location.hash = target;
      });
  });
});

除此之外我还有另一个链接的javascript文件(我认为不应该干扰平滑滚动代码。请帮助/建议选项。

1 个答案:

答案 0 :(得分:1)

&#13;
&#13;
$(document).ready(function() {
  $('a[href^="#"]').click(function(e) {
    e.preventDefault();

    var target = this.hash;
    var $target = $(target);

    if ($target.length === 0) {
      alert('No target!');
      return;
    }
    
    $('html, body').animate({
      scrollTop: $target.offset().top
    }, 900, 'swing', function() {
      window.location.hash = target;
    });
  });
});
&#13;
div[id*="sec"] {
  margin-bottom: 500px
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sec1">
  <span id="header">Heading</span>
  <!--<span id="notheader">Umesh meena is the coolest</span>-->
  <!--<div id="navbar" class="before">lol</div>-->
  <a href="#sec2" id="button1">link to the page</a>
  <a href="#sec3" id="button2">link to the page</a>
  <a href="#sec4" id="button3">link to no target</a>
</div>
<div id="sec2">
  <span id="main">lorem</span>
</div>
<div id="sec3">
  <span id="main">ipsum</span>
</div>
<div id="notarget">
  <span id="main">Vous aved un chat.</span>
</div>
&#13;
&#13;
&#13;