js实现移动端吸顶效果

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

js实现移动端吸顶效果

  2021-04-02 我要评论

今天来简单的写一个吸顶,供大家参考,具体内容如下

先罗列一下吸顶需要使用到的属性
** 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>

敬请期待 效果图示(正在制作中…)

您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们