用scrollTop实现固定定位

最新做项目时,遇到了让固定定位的实现,现整理为一个小demo

<!DOCTYPE html>
<html lang="en">

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

    #app {
      width: 500px;
      height: 400px;
      background-color: burlywood;
      overflow: auto;
    }

    .child1 {
      z-index: 1001;
      position: absolute;
      top: 0;
      width: 400px;
      height: 200px;
      background-color: chartreuse;
    }

    .child2 {
      padding-top: 200px;
      width: 400px;
      height: 400px;
      background-color: rgb(255, 0, 55);
    }

  </style>
</head>

<body>
  <div id="app">
    <div class="child1">222</div>
    <div class="child2">333</div>
  </div>
  <script>
    window.onload = function () {
      let app = document.getElementById("app").parentNode;
      let child1 = document.getElementsByClassName("child1")[0];
      app.addEventListener("scroll", function () {
        child1.style.top = app.scrollTop + "px";
      })
    }

  </script>
</body>

</html>

效果图如下:

 

posted @ 2020-11-26 10:24  yuwenjing  阅读(458)  评论(0编辑  收藏  举报