使用锚链接平滑滚动

时间:2016-11-02 22:27:59

标签: html css smooth-scrolling codepen

我想知道是否有人会使用一些简单的代码来获取我的锚点链接,并在点击时平滑地滚动到页面的该部分。现在,每当我点击我的链接时,它基本上都会传送到网页的那个部分而没有任何平滑的滚动。任何帮助将不胜感激,谢谢!

P.S。我在CodePen中这样做

1 个答案:

答案 0 :(得分:1)

您可以根据Chris Coyier's article和随附的codepen来尝试此jQuery脚本:

$(function() {
  $('a[href*="#"]:not([href="#"])').click(function() {
    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
        }, 1000);
        return false;
      }
    }
  });
});

请注意Chris'codepen中锚标记hrefs如何引用相关的h2 id。

发布您的codepen,我们可以看看。

相关问题