吸顶效果

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

效果图:

思路的难点:

第一步,先给滚动动作添加处理事件,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;
  width: 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;
  width: 300px;
  background: #fff;
}
</style>

  

 

posted @ 2021-05-17 09:50  qingshanyici  阅读(73)  评论(0编辑  收藏  举报