1. 程式人生 > 程式設計 >js實現移動端吸頂效果

js實現移動端吸頂效果

今天來簡單的寫一個吸頂,供大家參考,具體內容如下

先羅列一下吸頂需要使用到的屬性
** scrollTop 獲取當前滾動的距離(也就是盒子距離頂部的距離)
offsetTop 盒子距離頂部的高度
offsetHeight 盒子自身的高度
scrollY 滾動的距離
**

想要寫出一個吸頂 一定要先明白這幾個屬性哦(當然了,他也很簡單,相信您看完會有一定的收穫)

根據圖片中的思路來寫:

<!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 class="wrap">
    <div class="header">我是即將吸頂的哦</div>
    <div class="main"></div>
  </div>

  <script>
    const head = document.querySelector('.header');
    document.addEventListener('scroll',()=>{
      //console.log(document.documentElement.offsetTop) // 0 html距離頂部的距離
      //console.log(document.querySelector('.header').offsetHeight) // 40 紅盒子的高度
      //console.log(window.scrollY) // 滾動的距離
      if(window.scrollY > head.offsetHeight){
        head.classList.add('fixed')
      }
    })
  </script>
</body>
</html>

敬請期待 效果圖示(正在製作中…)

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。