我正在嘗試為我的 Angular 應用程式找到一個簡單的解決方案,以檢查某個元素在滾動時是否可見,以及是否會觸發一些影片。所以,通常我只使用 jQuerys Waypoint 插件。但這并不是真正的 Angular 方式。在從不同角度嘗試之后,我在這里遇到了這個 npm 包:ngui/common
該ngui-inview指令 正是我要找的,但檔案吮吸非常糟糕。它只是展示了我如何延遲加載影像......這不是我想要的。
這里有人有使用這個包的經驗嗎?我真的需要一些幫助
uj5u.com熱心網友回復:
使用相交觀察者:
// the element that you are observing (just add #yourElement in the template) for this query to work
@ViewChild('yourElement') yourElement: ElementRef;
ngAfterViewInit() {
const threshold = 0.2; // how much % of the element is in view
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
// run your animation code here
observer.disconnect(); // disconnect if you want to stop observing else it will rerun every time its back in view. Just make sure you disconnect in ngOnDestroy instead
}
});
},
{ threshold }
);
observer.observe(this.yourElement.nativeElement);
}
現在不需要任何額外的包/依賴項,這個特性是大多數現代瀏覽器的原生特性。
見https://caniuse.com/intersectionobserver
更多詳情:https : //developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/389070.html
