jQuery向下滚动功能不起作用

时间:2017-09-11 10:16:19

标签: javascript jquery

我收到以下错误:

  

未捕获的TypeError:无法读取属性' top'未定义的



$(document).ready(function() {
  $(function() {
    $('a[href*="#"]').on('click', function(e) {
      e.preventDefault();
      $('html, body').animate({
        scrollTop: $($(this).attr('href')).offset().top
      }, 500, 'linear');
    });
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="scrollDown">
  <a href="#nextSection"><span></span>toliau</a>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

只需更改此行,我希望它能正常工作

 scrollTop: $($(this).attr('href')).offset().top

到此

  scrollTop: $(this).offset().top

答案 1 :(得分:1)

$(document).ready(function() {
  $(function() {
    $('a[href*="#"]').on('click', function(e) {
      e.preventDefault();
      $('html, body').animate({
          scrollTop: $(this).offset().top
      }, 500, 'linear');
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="scrollDown">
  <a href="#nextSection"><span></span>toliau</a>
</div>