Angular路由器中的滚动效果

时间:2018-03-09 09:31:07

标签: angular scroll angular-routing

我正在尝试将Scrollspy效果添加到Angular项目中。当用户单击链接而不是将其显示为新页面时,该组件应向上滚动,下一个组件应该到达该位置。有没有办法在Angular中进行路由?单击链接后,页面应按照以下jquery代码

设置为scrolltop动画
$('html, body').animate({scrollTop: offsetTop}, 'normal');

Angular中是否有任何库或功能?

2 个答案:

答案 0 :(得分:3)

我正在寻找一些非常简单的处理滚动的东西,我最终制作了自己的指令:

@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编辑器的滚动。

答案 1 :(得分:0)

这是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);
        }
    }
}