一、引用fromEvent
import { fromEvent } from 'rxjs';
二、调用fromEvent
this.subscribeScoll = fromEvent(window, 'scroll') .subscribe((event) => { this.onWindowScroll(); }); onWindowScroll(){console.log(页面滚动了);};
三、调用滚动函数
详细代码:
import { Component, OnInit } from '@angular/core'; import { fromEvent } from 'rxjs'; //引入 @Component({ selector: 'app-heroes', templateUrl: './heroes.component.html', styleUrls: ['./heroes.component.css'] }) export class HeroesComponent implements OnInit { subscribeScoll:any; scrollDis:any = { _top:0 } constructor() { } ngOnInit() { this.subscribeScoll = fromEvent(window, 'scroll') .subscribe((event) => { this.onWindowScroll();//调用 }); } scollPostion() { var t, l, w, h; 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, w, height: h }; } onWindowScroll(){ this.scrollDis._top = this.scollPostion().top; console.log(this.scrollDis._top); } }