js 粘贴定位 滚动到顶部后,固定在头部

发布时间 2023-06-01 15:33:50作者: 沐阳歡

由于css的position:sticky的粘贴定位存在兼容性问题,因为决定使用js来判断盒子的位置,添加固定定位来解决,实例代码如下:

<!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>
</head>
<style>
body{
  outline: 1px solid;
}
.topclass{
  width: 100%;
  background: violet;
  height: 50px;
}
.title{
  width: 100%;
  background: rgb(50, 191, 38);
  height: 30px;
}
.content{
  width: 100%;
  background: rgba(24, 104, 233, 0.225);
  height: 2000px;
}
p{
  margin: 0;
}
</style>
<body>
  <div class="g-container">
    <div class="topclass">顶部</div>
    <div class="title">选项卡1454</div>
    <div class="content">
      <p>1i</p>
      <p>2i</p>
      <p>3i</p>
      <p>4i</p>
      <p>5i</p>
      <p>6i</p>
      <p>7i</p>
      <p>8i</p>
      <p>9i</p>
      <p>10i</p>
      <p>11i</p>
      <p>12i</p>
      <p>13i</p>
      <p>14i</p>
      <p>15i</p>
      <p>16i</p>
      <p>17i</p>
      <p>18i</p>
      <p>19i</p>
      <p>20i</p>
      <p>21i</p>
      <p>22i</p>
      <p>23i</p>
      <p>24i</p>
      <p>25i</p>
      <p>26i</p>
      <p>27i</p>
      <p>28i</p>
      <p>29i</p>
      <p>30i</p>
    </div>
  </div>
  <script>
    window.addEventListener("scroll",fun)
    function fun() {
      let dom = document.querySelector(".g-container")
      let rect = dom.getBoundingClientRect()
      let topclassBox = document.querySelector(".title")
      if(rect.top<-50){
        topclassBox.style.position = "fixed"
        topclassBox.style.top = 0  
      }
      if(rect.top>=-50){
        topclassBox.style.position = "relative"
        topclassBox.style.top = 0  
      }
    }
  </script>
</body>
</html>

注意点:不能直接监听要定位的盒子,最好在它外面再加一层,判断外层的盒子!