首页 > 解决方案 > 为什么 scrollTo 在我的 ClickListener 中有效,但在 AfterViewInit 中无效?

问题描述

我想知道为什么以下工作:

scroll(){
    window.scrollTo(0, this.ypos); // works perfectly fine
}

在我的 html.component 中:

<button (click)="scroll()">Scroll</button>

但以下不起作用:

ngAfterViewInit(){
    console.log(this.ypos); // is perfectly defined
    window.scrollTo(0, this.ypos); // won't work
}

有谁知道为什么它不起作用?window.scrollTo()也不起作用,ngOnInit但为什么?

标签: javascripthtmlangularscrollto

解决方案


不使用窗口对象,而是使用角度Viewportscroller服务滚动到指定位置。

组件.ts

   import { ViewportScroller } from '@angular/common';

   constructor(private viewportScroller: ViewportScroller) {}

   ngAfterViewInit(){
    this.viewportScroller.scrollToPosition([0,this.ypos]); 
   }

推荐阅读