css怎么实现平滑滚动效果

发布时间:2022-12-14 11:49:42 作者:iii
来源:亿速云 阅读:142

这篇文章主要讲解了“css怎么实现平滑滚动效果”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“css怎么实现平滑滚动效果”吧!

代码如下:

<!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;
}

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

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

感谢各位的阅读,以上就是“css怎么实现平滑滚动效果”的内容了,经过本文的学习后,相信大家对css怎么实现平滑滚动效果这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

推荐阅读:
  1. JS+CSS怎么实现滚动数字时钟效果
  2. 使用纯css来实现下拉菜单效果的案例

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

css

上一篇:iOS上css中fixed绝对定位实效怎么解决

下一篇:css怎么实现文本单行省略号和多行省略号效果

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》