Published on

吸顶效果实现

Authors
  • avatar
    Name
    谢克成
    Twitter

在网页中,对导航栏经常会用到吸顶效果,下面是简单使用 jQuery+css 实现简单的吸顶效果,还增加了节流函数,在多次滚动的情况下可以节约性能。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }

      .header,
      .nav,
      .con,
      .footer {
        margin: 0 auto;
      }

      .header,
      .footer {
        height: 200px;
        background-color: aquamarine;
      }

      .nav {
        height: 150px;
        background-color: pink;
      }

      .con {
        height: 2000px;
        background-color: bisque;
      }
    </style>
  </head>

  <body>
    <div class="header">header</div>
    <div class="nav">分类</div>
    <div class="con">内容</div>
    <div class="footer">footer</div>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
    <script>
      let divs = $('div')
      $(window).scroll(throttle(fn, 42))

      // 业务函数
      function fn() {
        let st = document.documentElement.scrollTop || document.body.scrollTop
        console.log('st', st)
        // 滚动条滚动大于200,则将header吸顶
        if (st > 200) {
          divs[1].style = 'position:fixed;top:0;width:100%'
        } else {
          divs[1].style = 'position:static'
        }
      }
      // 节流函数
      function throttle(callback, delay) {
        let flag = true
        return function () {
          if (flag) {
            setTimeout(() => {
              callback()
              flag = true
            }, delay)
          }
          flag = false
        }
      }
    </script>
  </body>
</html>