vue 2 上划吸顶 和 吸顶后 动态调整高度

122 阅读1分钟

效果: 吸顶前:

image.png

吸顶后

image.png

<template>
  <div>
    <div class="color_box">11111</div>
    <transition name="titles">
      <div @scroll="handleScroll" ref="title" :class="['title', 'sticky', flag? 'active':'' ]">
        使用 `position:sticky` 实现使用 `position:sticky` 实现使用 `position:sticky` 实现使用
        `position:sticky` 实现使用 `position:sticky` 实现使用 `position:sticky` 实现使用 `position:sticky` 实现使用
        `position:sticky` 实现使用 `position:sticky` 实现使用 `position:sticky` 实现使用 `position:sticky` 实现使用
        `position:sticky` 实现使用 `position:sticky` 实现
      </div>
    </transition>
    <div class="color_box_two">222</div>
  </div>
</template>


</script>
<script>
export default {
  data() {
    return {
      ele: null,
      throttleLoad: null,
      flag: false
    };
  },
  created() {},
  destroyed() {
    // 销毁
    window.removeEventListener("scroll", this.handleScroll);
  },
  mounted() {
    this.aa();
    window.addEventListener("scroll", this.handleScroll);
  },

  methods: {
    aa() {
      this.ele = this.$refs["title"];
    },
    handleScroll() {
      if (parseInt(this.ele.offsetTop - window.pageYOffset) == 0) {
        this.ele.style.height = "45px";
        this.flag = true;
      } else {
        this.ele.style.height = "100px";
        this.flag = false;
      }
    }
  }
};
</script>

<style>
.color_box {
  width: 100%;
  height: 100px;
  background: #333;
}

.title {
  width: 50%;
  /* height: .4px; */
  /* text-align: center; */
  /* line-height: .4px; */
  height: 100px;
  background: #999;
  color: #fff;
  position: absolute;
  font-size: 16px;
  overflow: hidden;
}

.sticky {
  position: -webkit-sticky;
  position: sticky;
  top: 0;
}

.active {
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.color_box_two {
  width: 100%;
  height: 1000px;
  background: -webkit-linear-gradient(
    top,
    #333333 20%,
    #999999 40%,
    #333333 80%
  );
}
</style>