【问题标题】:How to trigger an action based on the user's view on the page in Angular?如何根据用户在 Angular 页面上的视图触发操作?
【发布时间】:2021-05-28 01:54:06
【问题描述】:

我希望在 Angular 中有一个包含多个子部分的页面,可以通过无缝向下滚动或单击部分列表来访问这些子部分。 如果用户单击该部分,则会触发滚动到该部分的操作,并突出显示用户当前在页面中所在的特定部分。

如何通过滚动正确触发颜色突出显示来跟踪用户何时到达特定部分?

【问题讨论】:

    标签: javascript html css angular angular-material


    【解决方案1】:

    您可以通过@ViewChild 或@ViewChildren 获取您的部分。

    在 html 中用 <div #section>... 标记它们

    ts内部:

    ...
    @ViewChildren('section') sections: QueryList<ElementRef>; // getting your sections here
    
    @HostListener('scroll') scrolling() {
      this.checkScrollPosition();
    }
    
    @HostListener('resize') scrolling() {
      this.checkScrollPosition();
    }
    
    currentSectionId: number;
    
    constructor(private readonly renderer: Renderer2) {}
    
    checkScrollPosition(): void {
      // check if your inside your section here by using window.scrollTop and sections[anyIndex].nativeElement.scrollTop
    
      // if your using angular universal you can use Angulars ViewportScroller
    
    
      renderer.removeClass(sections[this.currentSectionId].nativeElement, 'class-with-color');
    
      this.currentSectionId = anyIndex // the index you got by searching for the current section
    
      renderer.addClass(sections[this.currentSectionId].nativeElement, 'class-with-color');
    } 
    
    

    HostListeners 观察调整大小和滚动事件以检查您是否在当前部分内。

    我懒得写如何找到当前部分,我希望这能回答你的问题:D

    ps。我还没有测试过代码,但它应该是这样的

    【讨论】:

    • 非常感谢!我不知道 HostListener,有了它就可以实现这个想法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-29
    • 2017-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    相关资源
    最近更新 更多