gpt4 book ai didi

javascript - Angular 5 anchor 没有滚动

转载 作者:行者123 更新时间:2023-11-30 11:23:25 25 4
gpt4 key购买 nike

我想做的是创建一个 anchor 链接。此链接将导航到我页面中的特定滚动点。我有 Angular 版本 5。

HTML:

<mat-list>
<mat-list-item><a [routerLink]="['/']"> Intro </a></mat-list-item>
<mat-list-item><a [routerLink]="['/']" fragment="mobile"> Mobile </a></mat-list-item>
...
</mat-list>

在 home.componets.ts 中:

export class HomeGrComponent implements OnInit {
private fragment: string;

constructor(private route: ActivatedRoute) { }

ngOnInit() {
this.route.fragment.subscribe(fragment => { this.fragment = fragment; });
}

ngAfterViewInit(): void {
try {
setTimeout(()=> {
document.querySelector('#' + this.fragment).scrollIntoView();
}, 1000);

} catch (e) { }
}
}

我从 this question 中获取了这段代码但它不起作用。网址更改为

http://localhost:4200/#mobile

但它没有滚动到我的观点。同样在控制台中有一个错误:

Cannot read property 'scrollIntoView' of null 

什么可能出错?如果您需要一些其他信息,请让我回复。滚动顺畅地导航(可选)也可能很棒。

最佳答案

您可以使用以下代码:

import { Component, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { filter } from 'rxjs/operators';
import { Subscription } from 'rxjs';

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnDestroy {
private sub: Subscription;

constructor(activeRoute: ActivatedRoute) {
this.sub = activeRoute.fragment.pipe(filter(f => !!f)).subscribe(f => document.getElementById(f).scrollIntoView());
}

public ngOnDestroy(): void {
if(this.sub) this.sub.unsubscribe();
}
}

工作 exampleCode behind

关于javascript - Angular 5 anchor 没有滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48923930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com