dom滚动时判断内部盒子与顶部的距离

1、给外层dom添加超出滑动样式并给ref

2、在mounted时通过refs找到该dom并添加滚动监听

3、设置位置标杆并给ref,当父盒子滚动的时,判断标杆离窗口顶部的距离

4、判断如果距离小于15,就把需要浮动的盒子浮动

1、html代码

<el-row>
  <!-- 左边盒子 -->
 <el-col :xl="18" :lg="18" :sm="16" :xs="14" class="pt-12 pr-12 pl-12 pos-rel border-box" ref="centerCol">
  <!-- 滑动的盒子 -->
  <div class="border-box h-100vh overflow-y-auto">
   <!-- 内容 -->
    <div class="topTabs topTabs2 mb-12">
     1
     <!-- 位置标杆 -->
      <div ref="centerTab"></div>
      <!-- 需要浮动的dom -->
      <div :class="positioning?'positioning':''" class="pl-12 pr-12">
       22222
       </div>
      1
    </div>
  </div>
 </el-col>
 <!-- 右边盒子 -->
 <el-col :xl="6" :lg="6" :sm="8" :xs="10" class="overflow-y-auto border-box pr-16 mt-12 h-100vh"></el-col>
</el-row>

html部分

mounted(开启监听盒子滚动)

  mounted() {
    let centerCol = this.$refs.centerCol.$el
    centerCol.addEventListener('scroll', this.myScroll, true)
  },

methods(滚动时判断标杆距与顶部的距离并做其他操作) 

  methods: {
    myScroll: _.throttle(function(event){
      const centerTab = this.$refs.centerTab
      // 获取目标元素到顶部的距离
      const elementDistanceToTop = centerTab.getBoundingClientRect().top + window.pageYOffset;
      console.log('目标元素到顶部的距禢:', elementDistanceToTop);
      if (elementDistanceToTop <= 15) {
        this.positioning = true
      } else {
        this.positioning = false
      }
    }, 500)
}

其中throttle方法,为lodash节流

需要引入(也可不要throttle直接用)

import _ from "lodash";

离开页面时要销毁!!!

destroyed() {
  centerCol.removeEventListener('scroll',this.myScroll, false);
},

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值