javascript - 为什么 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
但为什么?
解决方案
不使用窗口对象,而是使用角度Viewportscroller服务滚动到指定位置。
组件.ts
import { ViewportScroller } from '@angular/common';
constructor(private viewportScroller: ViewportScroller) {}
ngAfterViewInit(){
this.viewportScroller.scrollToPosition([0,this.ypos]);
}
推荐阅读
- .net - SignalR 的响应中的 C 值是什么意思?
- sql - 分母中的Count(*) -1 - sql
- javascript - BrowserStack Options App:执行期间的键值对错误
- amazon-web-services - 修复 Amazon EKS 集群中的 DataDog 代理拥塞问题
- sql - 将数据转换为带有编号字段的 JSON
- javascript - 为什么 Paper.js 的 `smooth: Continuous` 函数没有按预期工作?
- wordpress - 带有 pod 和 elementor 的 WordPress 目录
- python - 有条件地更新/插入字典的替代方法
- c++ - 如何正确解决 Windows API 和 DirectX API 以及微软开发的其他 API 之间的宏冲突 (GetMessage)
- java - 使用 @Value 注释的构造函数调用如何工作?