平滑回到顶部

方法一 CSS

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        html{
            scroll-behavior: smooth;
        }
    </style>
</head>

<body>

    <div id="backTop">返回顶部</div>
    <script>
        const backTop = document.getElementById('backTop');
        backTop.onclick = function(){
            window.scrollTo(0,0);
        }

        window.onscroll = function(){
            let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            if(scrollTop > 500){
                backTop.style.display = 'block';
            }else{
                backTop.style.display = 'none';
            }
        }
    </script>
</body>
</html>

方法二JS实现

const backTop = document.getElementById('backTop');
  backTop.onclick = ()=>{
      window.scrollTo({
          top:0,
          behavior:'smooth'
      })
  }

posted @ 2023-12-09 17:03  Laravel自学开发  阅读(13)  评论(0编辑  收藏  举报