[英]Intersection Observer API: Observe the center of the viewport
我試圖觀察視口中心的交點,我嘗試在 rootMargin 中傳遞負值
rootMargin: '-45% 10% -45%'
但它似乎不能正常工作。
我的要求是當我的元素到達屏幕中心時觀察交叉點。
交叉點觀察器 rootMargin 和交叉點的處理方式在幾次嘗試后可能會變得有點混亂,所以我將嘗試詳細說明如何在特定情況下實現這一點:
在視口中心相交元素的頂部/底部
const intersectionAtTopOrBottomElement = document.querySelector('.top-bottom-element');
const elementHasIntersected = (entries, o) => {...};
const ioConfiguration = {
/**
* This rootMargin creates a horizontal line vertically centered
* that will help trigger an intersection at that the very point.
*/
rootMargin: '-50% 0% -50% 0%',
/**
* This is the default so you could remove it.
* I just wanted to leave it here to make it more explicit
* as this threshold is the only one that works with the above
* rootMargin
*/
threshold: 0 //
};
const observer = new IntersectionObserver(elementHasIntersected, ioConfiguration);
observer.observe(intersectionAtTopOrBottomElement);
通過這樣做, elementHasIntersected
回調將在元素的最頂部或最底部邊緣與視口中心相交時被調用。
相當容易吧? 現在,如果您想實現類似的“中心交叉點”場景,例如:
然后,這將需要一種不同的方法作為rootMargin: '-50% 0% -50% 0%'
永遠不會允許在 50% 處觸發交集——因為元素永遠不會有 50% 可見。 如果它對您有價值,我很樂意就這個特定場景進行頭腦風暴,所以請告訴我。
這是我發布的一篇關於 Intersection Observer API和Intersection Observer Playground 的文章,我將它們放在一起,您可以在其中嘗試不同的配置(此版本有一些限制),也許您會找到所需的組合。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.