Trigger function when element is visible on screen (viewport)

半城伤御伤魂 提交于 2020-01-07 02:55:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!