加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何在Angular 4中处理窗口滚动事件?

发布时间:2020-12-17 07:06:27 所属栏目:安全 来源:网络整理
导读:我似乎无法捕获Window滚动事件. 在几个网站上,我发现代码与此类似: @HostListener("window:scroll",[])onWindowScroll() { console.log("Scrolling!");} 这些片段通常来自版本2.这在Angular 4.2.2中似乎不起作用(不再?).如果我将“window:scroll”替换为
我似乎无法捕获Window滚动事件.
在几个网站上,我发现代码与此类似:

@HostListener("window:scroll",[])
onWindowScroll() {
  console.log("Scrolling!");
}

这些片段通常来自版本2.这在Angular 4.2.2中似乎不起作用(不再?).如果我将“window:scroll”替换为“window:touchmove”,那么touchmove事件处理得很好.

有谁知道我错过了什么?非常感谢你!

解决方法

可能你的文档没有滚动,但里面有一个div.如果从文档调用滚动事件,则仅向窗口冒泡.此外,如果您从文档中捕获事件并调用stopPropagation之类的内容,则不会在窗口中收到事件.

如果要捕获应用程序中的所有滚动事件(也可能是来自微小的可滚动容器),则必须使用默认的addEventListener方法,并将useCapture设置为true.

这将在事件发生时触发事件,而不是泡沫阶段.不幸的是,坦率地说,一个很大的错过,angular不提供传递事件监听器选项的选项,因此你必须使用addEventListener:

export class WindowScrollDirective {

    ngOnInit() {
        window.addEventListener('scroll',this.scroll,true); //third parameter
    }

    ngOnDestroy() {
        window.removeEventListener('scroll',true);
    }

    scroll = (): void => {
      //handle your scroll here
      //notice the 'odd' function assignment to a class field
      //this is used to be able to remove the event listener
    };

}

现在这不是全部,因为所有主流浏览器(IE和Edge除外)都实现了新的addEventListener规范,这使得将对象传递为third parameter成为可能.

使用此对象,您可以将事件侦听器标记为被动.对于会激活大量时间的事件,这是一个建议的事情,这会干扰UI性能,如滚动事件.要实现此功能,您应首先检查当前浏览器是否支持此功能.在mozilla.org上,他们发布了一个方法passiveSupported,您可以使用该方法检查浏览器支持.但是,当您确定不打算使用event.preventDefault()时,您只能使用它

在我向您展示如何执行此操作之前,您可以想到另一个性能功能.为防止更改检测运行(每次在区域内发生异步时都会调用DoCheck.就像事件触发一样),您应该在区域外运行事件监听器,并且只在真正需要时才输入它.所以,让我们结合所有这些:

export class WindowScrollDirective {

    private eventOptions: boolean|{capture?: boolean,passive?: boolean};

    constructor(private ngZone: NgZone) {}

    ngOnInit() {            
        if (passiveSupported()) { //use the implementation on mozilla
            this._eventOptions = {
                capture: true,passive: true
            };
        } else {
            this.eventOptions = true;
        }
        this.ngZone.runOutsideAngular(() => {
            window.addEventListener('scroll',<any>this.eventOptions);
        });
    }

    ngOnDestroy() {
        window.removeEventListener('scroll',<any>this.eventOptions);
        //unfortunately the compiler doesn't know yet about this object,so cast to any
    }

    scroll = (): void => {
        if (somethingMajorHasHappenedTimeToTellAngular) {
           this.ngZone.run(() => {
               this.tellAngular();
           });
        }
    };   
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读