我们当前需要用到的方法是uni.createIntersectionObserver,创建后会包含4个方法
-
relativeTo(selector,[margins]) 使用选择器指定一个节点,作为参照区域之一
-
relativeToViewport([margins]) 指定页面显示区域作为参照区域之一
-
observe(selector,[callback]) 指定目标节点并开始监听相交状态变化情况。回调函数 callback 包含一个参数 result
-
disconnect() 停止监听。回调函数将不再触发
完整项目demo:https://gitee.com/hackchen/demo-collection/tree/master/front-end/uniapp/intersection-observer-demo
当前示例,我们用到3个方法,分别为relativeTo、observe、disconnect
完整代码如下:
<script setup>
import { ref,getCurrentInstance,onMounted } from 'vue'
import {onLoad, onUnload} from '@dcloudio/uni-app'
const observer = ref(null);
const appear = ref(false);
const instance = ref(null);
onMounted(() => {
instance.value = getCurrentInstance();
console.log('onMounted',instance.value)
observer.value = uni.createIntersectionObserver(instance.value);
// 如果 .ball 出现在 .scroll-view 可视区域,则执行回调
observer.value
.relativeTo('.scroll-view') // 第二个参数 定义相交边界 left top right bottom
.observe('.ball', (res) => {
console.log('createIntersectionObserver res',res)
// res.intersectionRatio 0-1 相交比例 大于0 小球出现
if (res.intersectionRatio > 0 && !appear.value) {
appear.value = true;
} else if (!res.intersectionRatio > 0 && appear.value) {
appear.value = false;
}
})
})
onUnload(() => {
observer.value.disconnect();
})
</script>
<template>
<view class="container">
<text>{{ appear ? '小球出现' : '小球消失' }}</text>
<view class="page-section">
<scroll-view class="scroll-view" scroll-y>
<view class="scroll-area">
<text class="notice">向下滚动让小球出现</text>
<view class="ball"></view>
</view>
</scroll-view>
</view>
</view>
</template>
<style lang="scss" scoped>
.container {
display: flex;
flex-direction: column;
}
.scroll-view {
height: 400rpx;
background: #fff;
border: 1px solid #ccc;
box-sizing: border-box;
}
.scroll-area {
height: 1800rpx;
display: flex;
flex-direction: column;
align-items: center;
transition: .5s;
}
.notice {
margin: 150rpx 0 400rpx 0;
}
.ball {
width: 200rpx;
height: 200rpx;
background: #1AAD19;
border-radius: 50%;
}
</style>