zoukankan      html  css  js  c++  java
  • 吸顶效果

    当页面滚动到某一个特定位置的时候,标题栏就始终保持到顶部固定位置,当页面滚回到某一个特定位置的时候,标题栏再恢复到原来的状态。

    效果图:

    思路的难点:

    第一步,先给滚动动作添加处理事件,handleScorll事件

    第二步,事件获取的高度,是两个属性,scrollTop和元素的高度位置offsetTop

    这个地方有个问题,就是获取的scrollTop始终为零,本质原因还是因为没有获取到对应的元素

    参考文档:https://blog.csdn.net/kouryoushine/article/details/99745904

    第三步:固定元素位置,用fixed,不要用absolute

    代码:

    <template>
      <div ref="container" class="container">
        <div class="swiper">轮播图</div>
        <div ref="header" :class="['header', { fixed: headerFix }]">标题</div>
        <div class="list-wrap">
          <ul>
            <li v-for="(item, index) in dataList" :key="index">{{ item }}</li>
          </ul>
        </div>
      </div>
    </template>
    
    <script>
    export default {
      data() {
        return {
          dataList: ["苹果", "梨", "香蕉", "橘子"],
          headerFix: false,
        };
      },
      created() {
        this.listenerFunction();
      },
      beforeDestroy() {
        document.removeEventListener("scroll", this.handleScroll);
      },
    
      methods: {
        listenerFunction(e) {
          document.addEventListener("scroll", this.handleScroll, true);
        },
        handleScroll() {
          // 已经滚动的距离,为什么总是scrollTop为0
          let scrollTopHeight = this.$refs.container.scrollTop;
          let headerLocation = this.$refs.header.offsetTop;
          this.headerFix = scrollTopHeight > headerLocation ? true : false;
          scrollTopHeight > headerLocation
            ? console.log("fixed")
            : console.log("unfixed");
        },
      },
    };
    </script>
    
    <style lang="scss" scoped>
    .container {
      position: relative;
      top: 30px;
      left: 200px;
       300px;
      height: 400px;
      text-align: center;
      overflow: auto;
      border: 1px solid #000;
      .swiper {
        height: 200px;
        line-height: 200px;
        background: pink;
      }
      .header {
        height: 50px;
        line-height: 50px;
        border: 1px solid blue;
      }
      .list-wrap {
        li {
          height: 300px;
          line-height: 300px;
          margin-top: 10px;
          border: 1px solid #000;
          &:first-child {
            margin-top: 0px;
          }
        }
      }
    }
    .fixed {
      position: fixed;  
      top: 30px;
       300px;
      background: #fff;
    }
    </style>
    

      

  • 相关阅读:
    Netty源码分析之ByteBuf引用计数
    GitHub git push大文件失败(write error: Broken pipe)完美解决
    Windows10 Docker安装详细教程
    全面的Docker快速入门教程
    十本你不容错过的Docker入门到精通书籍推荐
    CentOS 8.4安装Docker
    postgres之一条sql查询总数及部分数据
    neo4j相关操作
    git上传大文件
    分布式文件系统fastdfs安装以及python调用
  • 原文地址:https://www.cnblogs.com/qingshanyici/p/14765892.html
Copyright © 2011-2022 走看看