【Html】js+css实现平滑滚动

效果

在这里插入图片描述

示例

<!DOCTYPE html>
<html>
  <head>
    <title> Document </title>
    <style>
      button{
        bottom: 0;
        position: fixed;
        z-index: 999;
        left: 0;
        background: rgb(94, 171, 255);
        border: 1px red;
        color: white;
        font-size: large;
        font-family: '';
      }
    img{
      position: relative;
      cursor: not-allowed;
      width: 100%;
      height: 100%;
      z-index: 0;
    }
    /*方式一:配合 “window.scrollTo(0,0);” 一起设置滚动行为:平滑*/
     html{
      scroll-behavior: smooth;
    } 
  </style>
  </head>
  <body>
    <button class="btn">回到顶部</button>
    <img src="https://picsum.photos/seed/1/800/600.jpg" alt=""/>
    <img src="https://picsum.photos/seed/2/800/600.jpg" alt=""/>
    <img src="https://picsum.photos/seed/3/800/600.jpg" alt=""/>
    <img src="https://picsum.photos/seed/4/800/600.jpg" alt=""/>
    <img src="https://picsum.photos/seed/5/800/600.jpg" alt=""/>
    <img src="https://picsum.photos/seed/6/800/600.jpg" alt=""/>
    <img src="https://picsum.photos/seed/7/800/600.jpg" alt=""/>
    <img src="https://picsum.photos/seed/8/800/600.jpg" alt=""/>
    <img src="https://picsum.photos/seed/9/800/600.jpg" alt=""/>
    <img src="https://picsum.photos/seed/10/800/600.jpg" alt=""/>
    <script>
    const btn = document.querySelector('.btn');
    btn.onclick = () => {
      //直接回到顶部
      window.scrollTo(0,0);

      /* 方式二:设置滚动到顶部行为:平滑*/
      /* window.scrollTo({
        top:0,
        behavior:"smooth"
      }); */
    }
  </script>
  </body>
</html>

推荐两种方式

方式一

第一步、使用js设置滚动位置

window.scrollTo(0,0);设置为滚动位置为x=0,y=0

    <script>
    const btn = document.querySelector('.btn');
    btn.onclick = () => {
      //直接回到顶部
      window.scrollTo(0,0);
    }
  </script>

第二步、使用css设置html的滚动行为

     html{
      scroll-behavior: smooth;
    } 

方式二

直接使用window.scrollTo设置滚动位置及滚动行为

      window.scrollTo({
        top:0,
        behavior:"smooth"
      });