使用 jQuery 添加网页锚文本平滑滚动效果

来自:互联网
时间:2018-11-14
阅读:

我们浏览一些网站的时候,会发现点击导航条上的链接的时候,页面会非常平滑的滚动网页下面相应的位置,相对于浏览器默认的一下子跳过去,用户体验无疑友好了许多,其实显示这种效果只需要简单的一段 jQuery 代码。

smooth-scroll

$(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;
      }
    }
  });
});

在结合点击回到顶部的功能,一个非常漂亮切用户体验非常友好的单页面导航效果就出来了。

返回顶部
顶部