代码之家  ›  专栏  ›  技术社区  ›  Mujahid

角度路由器中的Scrollspy效应

  •  3
  • Mujahid  · 技术社区  · 8 年前

    我正在尝试将Scrollspy效果添加到角度项目中。当用户单击某个链接而不是将其显示为新页面时,该组件应该向上滚动,下一个组件应该出现在该位置。有没有一种方法可以与布线成角度?当单击链接时,页面应显示为scrolltop,如下jquery代码所示

    $('html, body').animate({scrollTop: offsetTop}, 'normal');
    

    Angular中是否有库或功能?

    2 回复  |  直到 8 年前
        1
  •  4
  •   ibenjelloun    5 年前

    我一直在寻找一些非常简单的方法来处理滚动,最后我制定了自己的指令:

    @Directive({
      selector: '[scrollSpy]'
    })
    export class ScrollSpyDirective {
      @Input() public spiedTags = [];
      @Output() public sectionChange = new EventEmitter<string>();
      private currentSection: string;
    
      constructor(private _el: ElementRef) {}
    
      @HostListener('scroll', ['$event'])
      onScroll(event: any) {
        let currentSection: string;
        const children = this._el.nativeElement.children;
        const scrollTop = event.target.scrollTop;
        const parentOffset = event.target.offsetTop;
        for (let i = 0; i < children.length; i++) {
          const element = children[i];
          if (this.spiedTags.some(spiedTag => spiedTag === element.tagName)) {
            if (element.offsetTop - parentOffset <= scrollTop) {
              currentSection = element.id;
            }
          }
        }
        if (currentSection !== this.currentSection) {
          this.currentSection = currentSection;
          this.sectionChange.emit(this.currentSection);
        }
      }
    }
    

    Here is a demo link with routing integrated. 出于某种原因, the stackblitz edition version 中断stackblitz编辑器的滚动。

        2
  •  1
  •   Carlos Silva    6 年前

    以下是Angular 9的工作版本:

    import { Directive, Input, EventEmitter, Output, ElementRef, HostListener } from '@angular/core';
    
    @Directive({
        selector: '[scrollSpy]'
    })
    
    export class ScrollSpyDirective {
        @Input() public spiedTags = [];
        @Output() public sectionChange = new EventEmitter<string>();
        private currentSection: string;
    
        constructor(private _el: ElementRef) {}
    
        @HostListener('window:scroll', ['$event'])
        onScroll(event: any) {
            let currentSection: string;
            const children = this._el.nativeElement.children;
            const scrollTop = event.target.scrollingElement.scrollTop;
            const parentOffset = event.target.scrollingElement.offsetTop;
            for (let i = 0; i < children.length; i++) {
                const element = children[i];
                if (this.spiedTags.some(spiedTag => spiedTag === element.tagName)) {
                    if ((element.offsetTop - parentOffset) <= scrollTop) {
                        currentSection = element.id;
                    }
                }
            }
    
            if (currentSection !== this.currentSection) {
                this.currentSection = currentSection;
                this.sectionChange.emit(this.currentSection);
            }
        }
    }
    
    推荐文章