import { appearFn } from 'appear-fn'
// 需要注意的是 , 该方法要等 Dom 加载完成再调用 . 比如在 Vue 中 , 你应该写在 onMounted() 或者 nextTick() 等确定 dom 已经挂载完成的地方
const config = {
appearFn: (el) => {
console.log(el, '出现');
},
disappearFn: (el) => {
console.log(el, '消失');
},
options: {
threshold: .6
},
unobserve: false
}
appearFn('#target', config)
<template>
<div id="rootEl">
<div class="a" style="width: 50%;height: 80%;background: green;"></div>
<div class="a" style="width: 50%;height: 80%;background: blue;"></div>
<div class="a" style="width: 50%;height: 80%;background: yellow;"></div>
<div class="a" style="width: 50%;height: 80%;background: red;"></div>
<div class="b" style="width: 50%;height: 80%;background: red;"></div>
</div>
</template>
<script setup>
import { nextTick } from 'vue'
import { appearFn } from 'appear-fn'
nextTick(() => {
const config = {
appearFn: (el) => {
console.log(el.id, '出现');
},
disappearFn: (el) => {
console.log('消失');
},
options: {
root: '#rootEl',
rootMargin: '0px 0px 0px 0px',
threshold: .5 // 元素出现一半时 才会被视为 "出现" 了
},
unobserve: false
}
appearFn('.a, .b', config)
})
</script>
<style lang="scss" scoped>
#rootEl {
height: 50vh;
overflow: auto;
border: 1px solid red;
}
.a {
margin-bottom: 10px;
}
</style>