652° 2013213字0条评论

同页面中的平滑滚动

做个备份:同页面中 a 标签的平滑滚动。
来源:Smooth Scrolling

</head> 前插入 jQuery:

<script src='http://code.jquery.com/jquery-1.10.2.min.js' type='text/javascript'/>

</body> 前插入平滑滚动代码:

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

2017.10.12更新:如果想要更改滚动位置,可以修改scrollTop: target.offset().topscrollTop: target.offset().top-n,其中n即是距离顶部的像素。比如想要将滚动后停止的位置设为距离顶部50px处,那么代码就是scrollTop: target.offset().top-50


2020.06.14更新:更简洁的办法,在css中加入scroll-behavior: smooth;

EOF
890°
Blogger 添加相关文章
Comments
Write a Comment
点击加载Disqus