css平滑滚动 scroll-behavior: smooth;

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>锚点平滑跳转</title>

  <style>
    * {
      margin: 0;
      padding: 0;
    }

    html {
      scroll-behavior: smooth;
    }

    nav {
      width: 50%;
      height: 50px;
      text-align: center;
      position: fixed;
      left: 50%;
      transform: translateX(-50%);
      top: 0;
      background: green;
    }

    nav a {
      display: inline-block;
      line-height: 50px;
      color: #FFF;
      text-decoration: none;
      padding: 0 30px;
    }


    .box {
      width: 100%;
      text-align: center;
      font-size: 30px;
      color: #FFF;
    }

    #box1 {
      background: #d00;
    }

    #box2 {
      background: #42a4ff;
    }

    #box3 {
      background: #008080;
    }

    #to-top {
      position: fixed;
      bottom: 20px;
      right: 20px;
      border-radius: 50%;
      width: 80px;
      height: 80px;
      background: #ccc;
      color: #666;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
    }
  </style>
</head>

<body>
  <nav>
    <a href="#box1">box1</a>
    <a href="#box2">box2</a>
    <a href="#box3">box3</a>
  </nav>

  <div id="box1" class=" box">box1</div>
  <div id="box2" class=" box">box2</div>
  <div id="box3" class=" box">box3</div>

  <div id="to-top">回到顶部</div>

  <script>
    onload = function () {
      const _Height = document.documentElement.clientHeight;
      const Box = document.getElementsByClassName('box');

      for (var i = 0; i < Box.length; i++) {
        Box[i].style.height = _Height + 'px'
        Box[i].style.lineHeight = _Height + 'px'
      }

      document.querySelector('#to-top').onclick = function (el) {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      }
    }
  </script>
</body>

</html>

主要

html {
 scroll-behavior: smooth;
}

这样,在回到顶部的时候,会有动画不会立即过去,或有渐变动画
锚点,切换屏幕的时候也会有动画

 document.querySelector('#to-top').onclick = function (el) {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值