IntersectionObserver的实用功能

需求

        当数据覆盖背景图(固定的,不随着滚动)时,需要顶部tab栏固定,也就是监听数据滚动,触发一个事件来满足需求

 

tab栏就没写了,比较懒

样式实现

<template>
  <div class="App">
    <div class="bg"></div>
    <div class="content">
      <ul>
        <li>1</li>
        <li>1</li>
        <li>1</li>
        <li>1</li>
        <li>1</li>
        <li>1</li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {};
</script>

<style lang="css" scoped>
.App {
  width: 500px;
}
.bg {
  width: 500PX;
  height: 100px;
  background-color: red;
}
.content {
  height: 500px;
  overflow: auto;
  margin-top: -100px;
}
li {
  background-color: darkcyan;
  margin: 100px 0;
}
</style>

思路

        在数据上方加一个元素,覆盖在背景图上,就把这个元素类比于背景图,只要监听这个元素就行了

实现

<template>
  <div class="App">
    <div class="bg"></div>
    <div class="content">
      <div class="scroll" ref="scroll"></div>
      <ul>
        <li>1</li>
        <li>1</li>
        <li>1</li>
        <li>1</li>
        <li>1</li>
        <li>1</li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {

    }
  },

  mounted() {
    this.scroll()
  },

  methods: {
    scroll () {
      const scroll = this.$refs.scroll
      var observer = new IntersectionObserver(arr => {
      if (!arr[0].isIntersecting) {
        console.log(111);
        // 不再监听  只监听一次
        // observer.unobserve(scroll) // 可以根据需求取消监听,比如列表数据加载完成后,取消监听
      }
      // rootMargin 提前 100px 来发请求获取数据,因为发请求也是需要时间的
    }, { rootMargin: '100px' })
    // 调用函数,开始监听
    observer.observe(scroll)
    }
  }
};
</script>

<style lang="css" scoped>
.App {
  width: 500px;
}
.bg {
  width: 500PX;
  height: 100px;
  background-color: red;
}
.content {
  height: 500px;
  overflow: auto;
  margin-top: -200px;
}
.scroll {
  height: 100px;
}
li {
  background-color: darkcyan;
  margin: 100px 0;
}
</style>

IntersectionObserver使用起来就是比较麻烦,效果还是可以实现的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值