1. 程式人生 > 其它 >vue中實現元素吸頂效果

vue中實現元素吸頂效果

效果圖:

注意:視窗會抖動,體驗不是很好,後期再優化

程式碼實現:

<template>
  <div>
    <div style="height: 100px;"></div>
    <div
      style="width:100px;height:100px;margin-left:30px;border:1px solid red;color:black"
      :class="{isFixed:isFixed}"
    >scrollTop:{{scrollTop}}</div>
    <div style="height: 1000px;"></div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      isFixed: false,
      scrollTop: ""
    };
  },
  mounted() {
    window.addEventListener("scroll", this.handleScroll);
  },
  methods: {
    handleScroll() {
      this.scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      if (this.scrollTop >= 100) {
        this.isFixed = true;
      } else {
        this.isFixed = false;
      }
    }
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  }
};
</script>
<style lang="scss" scope>
.isFixed {
  position: fixed;
  top: 0;
  background-color: yellow;
  z-index: 999;
}
</style>