问题
jQuery has the plugin appear or waypoint to detect if element is visible or not in viewport. I did some research, I can not find and wonder if Angular2 has a similar plugin. If not yet, what is the best way to do something like that?
回答1:
This is how I do it:
sync-dom.utils.ts
static isInViewPort(rect: ClientRect, threshold = 0) {
return rect &&
rect.height &&
rect.top + rect.height + threshold >= 0 &&
rect.left + rect.width + threshold >= 0 &&
rect.bottom - rect.height - threshold <= SyncDomUtils.windowHeight &&
rect.right - rect.width - threshold <= SyncDomUtils.windowWidth;
}
dom.utils.ts
async isInViewPort(rect: ClientRect) {
return SyncDomUtils.isInViewPort(rect);
}
and in your component you do:
async isInViewPort() {
// you have to import the Renderer and ElementRef from angular/core
this.boundingRect = await this.domElementUtils
.invokeElementMethod(this.renderer, this.el.nativeElement, 'getBoundingClientRect');
return await this.domUtils.isInViewPort(this.boundingRect);
}
and use that function as this.isInViewPort() and it will return a boolean
this is the invokeElementMethod
I have in a dom-element.utils.ts
async invokeElementMethod<T extends keyof HTMLElement>(renderer: Renderer, element: any, methodName: T, args?: any[]) {
return await renderer.invokeElementMethod(element, methodName, args) as any;
}
来源:https://stackoverflow.com/questions/43673986/trigger-function-when-element-is-visible-on-screen-viewport