监听滚动条滚动
ponent.ts
import { fromEvent } from 'rxjs';export class AppComponent implements OnInit {subscribeScoll: any;scrollDis: any = {_top: 0};constructor(private router: Router) {}ngOnInit() {// 监听滚动条滚动this.subscribeScoll = fromEvent(window, 'scroll').subscribe((event) => {this.onWindowScroll(); // 调用});}// 获取滚动条滚动的位置scollPostion() {let t: any;let l: any;let w: any;let h: any;if (document.documentElement && document.documentElement.scrollTop) {t = document.documentElement.scrollTop;l = document.documentElement.scrollLeft;w = document.documentElement.scrollWidth;h = document.documentElement.scrollHeight;} else if (document.body) {t = document.body.scrollTop;l = document.body.scrollLeft;w = document.body.scrollWidth;h = document.body.scrollHeight;}return {top: t,left: l,width: w,height: h};}// 获取不同方向上滚动的距离onWindowScroll() {this.scrollDis._top = this.scollPostion().top;console.log(this.scrollDis._top);}}
路由跳转页面滚动到顶部
ponent.ts
import { Component, OnInit } from '@angular/core';import { Router } from '@angular/router';@Component({selector: 'app-root',templateUrl: './ponent.html',styleUrls: ['./ponent.scss']})export class AppComponent implements OnInit {constructor(private router: Router) {}ngOnInit() {this.router.events.subscribe((event) => {document.documentElement.scrollTop = 0;document.body.scrollTop = 0;});}}