本文主要介绍在Taro中实现监控元素在可视界面顶部移出隐藏,兼容微信小程序和h5
微信小程序
在微信小程序中实现主要依靠Taro.createIntersectionObserver,调用此方法会返回一个IntersectionObserver实例,此实例有一系列的方法监控元素的可见性。
这里主要使用relativeToViewport方法,它指定页面显示区域作为参照区域之一。
微信小程序中的页面显示区域不包含小程序自带的NavigationBar(顶部导航栏)和TabBar(底部导航栏)。如果你的NavigationBar是自定义的,那么参照区域应该减去自定义NavigationBar的高度。
const observer = Taro.createIntersectionObserver(this)
observer.relativeToViewport({top: -NavigationBarHeight})
然后使用observe方法监听元素
const observer = Taro.createIntersectionObserver(this)
observer
.relativeToViewport({top: -NavigationBarHeight})
.observe(`#${nodeId}`, (res) => {
const { boundingClientRect, intersectionRatio } = res;
//boundingClientRect:元素的布局信息,
//intersectionRatio:目标元素与参照元素的相交比例
const isShow =
//NavigationBarHeight:如果使用了自定义导航栏,为导航栏的高度,否则为0
boundingClientRect.top > NavigationBarHeight || intersectionRatio > 0;
setShow(isShow);
});
H5
在H5中不支持Taro.createIntersectionObserver方法,所以应该使用H5中对应的Api,Intersection Observer。
和微信小程序相比,用法差不多
首先创建一个新的IntersectionObserver对象
const observer = new IntersectionObserver(
function (entries) {
const observeNode = entries[entries.length - 1];
//isIntersecting:目标元素与参照元素是否相交
//boundingClientRect:元素的布局信息
setShow(
observeNode.isIntersecting ||
observeNode.boundingClientRect.top >= NavigationBarHeight,
);
},
{
//如果使用了自定义导航栏,减去它的高度
rootMargin: `-${safeTop}px 0px 0px `,
//所监听对象的具体祖先元素,如果未传入值或值为`null`,则默认使用顶级文档的视窗。
//root:node,
},
)
监听元素
const node = document.querySelector(`#${nodeId}`);
if (node) {
observer.current.observe(node);
}