angular的滚动检测和窗口大小变化检测

滚动检测

  // 监听滚动事件
  scrolling: any
  ngOnInit() {
    this.scrolling = fromEvent(window, 'scroll') // fromEvent(element,event)
      .subscribe((event) => { // 订阅
        this.onScroll()
      })
  }
  onScroll () {
    this.scrollTop = document.documentElement.scrollTop
    this.elementScrollTop = this.height
    // console.log(this.scrollTop)
    if (this.scrollTop >= (this.elementScrollTop)) {
      this.nav.nativeElement.style.cssText = "position:fixed;z-index:2;top:0;width:102%;"
    } else {
      this.nav.nativeElement.style.cssText = "position:relative;"
    }
  }

窗口大小变化

  // 监听窗口大小变化
  resized: any
  ngOnInit() {
    this.sliderHeight.emit(this.slider.nativeElement.offsetHeight)
    this.resized = fromEvent(window, 'resize')
    .subscribe((event)=>{
      this.sliderHeight.emit(this.slider.nativeElement.offsetHeight)
    })
  }

猜你喜欢

转载自www.cnblogs.com/foreversimon/p/12236932.html