vue吸顶效果

最上方 :class = "{'is_fixed': isFixed}" 它所在的div是我们需要固定的盒子

下方 <div id="boxFixed"></div> 相当于一个标志,当滚动超出这里时,上方div则固定

在data中定义两个变量

data() {
  return {
    isFixed: false,
    offsetTop: 0,
  }
}
mounted() {
    window.addEventListener('scroll', this.initHeight);
    this.$nextTick(() => {
      //获取对象相对于版面或由 offsetTop 属性指定的父坐标的距离顶端位置 
      this.offsetTop = document.querySelector('#boxFixed').offsetTop;
    })
},
//回调中移除监听
destroyed() {
    window.removeEventListener('scroll', this.handleScroll)
},
methods: {
    initHeight() {
    // 设置或获取位于对象最顶端和窗口中可见内容的最顶端之间的距离 (被卷曲的高度)
      var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
    //如果被卷曲的高度大于吸顶元素到顶端位置 的距离
      this.isFixed = scrollTop > this.offsetTop ? true : false;
  }
}

最后还需要注意固定时div的样式

.is_fixed{
   width: 100%;
   position: fixed;
   top: 0;
   z-index: 999;
}

猜你喜欢

转载自www.cnblogs.com/wurui-0922/p/12956767.html