组件吸顶功能实现

276 阅读1分钟

起因

页面被卷去头部存在兼容性问题,因此有如下写法:

document.documentElement.scrollTop
document.body.scrollTop(ie)
window.pageYOffsett(ie版本>9>
<template>
  <div class="home">
    <div ref="headerRef" class="header" :class="{ fixed: isFixed }">Header</div>
    <div style="height: 500px">111</div>
    <div style="height: 300px">222</div>
    <div>333</div>
  </div>
</template>

<script>
export default {
  name: 'home',
  data() {
    return {
      offsetTop: 0,
      offsetHeight: 0,
      isFixed: false
    }
  },
  mounted() {
    this.$nextTick(() => {
      // 获取吸顶元素的dom
      const header = this.$refs.headerRef
      // 吸顶元素到top的距离
      this.offsetTop = header.offsetTop
      // 元素自身的高度
      this.offsetHeight = header.offsetHeight
      // 监听滚动条
      window.addEventListener('scroll', this.handleScroll)
    })
  },
  destroyed() {
    // 自定义事件需要销毁!
    window.removeEventListener('scroll', this.handleScroll)
  },
  methods: {
    handleScroll() {
      // 得到页面滚动的距离,兼容写法
      const scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop
      // 判断页面滚动的距离是否大于吸顶元素的位置
      this.isFixed = scrollTop > this.offsetTop - this.offsetHeight
    }
  }
}
</script>

<style lang="scss">
.header {
  font-size: 30px;
  background-color: pink;
  &.fixed {
    position: fixed;
    top: 0px;
    left: 0px;
    right: 0px;
    z-index: 4;
  }
}
</style>