JS to achieve the effect of mobile terminal ceiling

Time:2020-10-2

Today to write a simple ceiling, for your reference, the specific content is as follows

First of all, list the attributes that need to be used for ceiling
**Scrolltop gets the current scrolling distance (that is, the distance from the box to the top)
Offset top the height of the box from the top
Offset height the height of the box itself
Scroll the distance to scroll
**

If you want to write a ceiling, you must first understand these attributes (of course, it is also very simple, I believe you will have some harvest after reading it)

Write according to the ideas in the picture:

<!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>
    *{
      margin:0;
      padding:0;
      box-sizing:border-box;
    }

    .wrap{
      overflow-y:scroll;
    }

    .header{
      width: 100%;
      height: 40px;
      background: lightgreen;
      color:#fff;
      text-align: center;
      line-height: 40px;
    }
    
    .main{
      height: 1000px;
      background: lightyellow;
    }

    .fixed{
      position: fixed;
      top:0;
    }

  </style>
</head>
<body>
  <div>
    < div > I'm going to be on top
    <div></div>
  </div>

  <script>
    const head = document.querySelector('.header');
    document.addEventListener('scroll',()=>{
      // console.log ( document.documentElement.offsetTop )// 0 HTML distance from top
      // console.log ( document.querySelector ('. Header'). OffsetHeight) // 40 height of the red box
      // console.log ( window.scrollY )// rolling distance
      if(window.scrollY > head.offsetHeight){
        head.classList.add('fixed')
      }
    })
  </script>
</body>
</html>

Please look forward to the effect icon (in production…)

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.