js节流函数 + 过渡动画实现回到顶部效果

节流函数: 我理解的节流就是减少代码的执行频率,保证一段时间内只执行一次代码。

一个返回顶部的案例

<!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>
      * {
        margin: 0;
        padding: 0;
      }
      img {
        max-width: 99%;
        max-height: 500px;
        float: left;
        padding: 20px;
        box-sizing: border-box;
      }
      .backTop {
        position: fixed;
        bottom: 50px;
        right: -150px;
        padding: 10px;
        background-color: #ccc;
        cursor: pointer;
        display: none;
        transition: all 0.5s;
      }
      .backTop:hover {
        background-color: blueviolet;
        color: #fff;
      }
      .box {
        width: 100%;
        height: 550px;
        overflow-y: auto;
        padding-bottom: 10px;
      }
    </style>
  </head>
  <body>
    <div class="box"></div>
    <div class="backTop">
      回到顶部
    </div>
    <script>
      setTimeout(() => {
        document.querySelector(".box").innerHTML = `
      



























`
; }, 100); const box = document.querySelector(".box"); const backTop = document.querySelector(".backTop"); let flag = true; box.onscroll = () => { if (flag) { console.log("滚动事件执行代码"); if (box.scrollTop > 1300) { backTop.style.right = "50px"; backTop.style.display = "block"; } else { backTop.style.right = "-150px"; backTop.style.display = "block"; } flag = false; setTimeout(() => { flag = true; }, 300); } }; backTop.onclick = () => { let scrollToptimer = setInterval(function () { var top = box.scrollTop; var speed = top / 5; if (box.scrollTop != 0) { box.scrollTop -= speed; } if (top == 0) { clearInterval(scrollToptimer); } }, 30); }; </script> </body> </html>

你可能感兴趣的:(js,css)