实现锚点的带动画效果---不是突然跳转到指定地方

html代码:

<div class="header">
  <img class="logo" src="./images/logo@2x.png" />
  <ul class="nav-list">
      <!-- href作锚点用,id是JS时用,必须是a便签的时候来进行锚链接-->
      <li class="sel"><a href="#home" id="nav-home">首页</a></li>
      <li><a href="#service" id="nav-ser">服务优势</a></li>
      <li><a href="#about" id="nav-about">关于我们</a></li>
      <li class="last"><a href="#contact" id="nav-con">联系我们</a></li>
  </ul>
</div>
<div class="banner"></div>
<div class="content" id="service">

</div>

JS代码:

$(function () {
  $("#nav-ser,#nav-about,#nav-con,#nav-home").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) {
        var targetOffset = $target.offset().top;
        $('html,body').animate({ scrollTop: targetOffset }, 800);
        return false;
      }
    }
  });
});

 

posted @ 2019-11-26 15:17  维维WW  阅读(1168)  评论(0编辑  收藏  举报