滚动时的Angular 5粘性菜单

时间:2018-05-28 10:02:39

标签: javascript html css angular typescript

当菜单到达页面顶部时,我会将菜单位置更改为固定。这是我的进展方式。

import { Component, OnInit, Inject, HostListener } from '@angular/core';
import {Location} from '@angular/common';
import { DOCUMENT } from "@angular/platform-browser";
....
export class DashboardComponent implements OnInit {
  constructor(private _location: Location, @Inject(DOCUMENT) private doc: Document) { }
  public fixed: boolean = false; 
  @HostListener("window:scroll", [])
  onWindowScroll() {
    let num = this.doc.body.scrollTop;
    console.log("scroll top" , this.doc.body.scrollTop)
    if ( num > 50 ) {
        this.fixed = true;
    }else if (this.fixed && num < 5) {
        this.fixed = false;
    }
  }
HTML

中的

<div [class.menus]="fixed">
  <div class="left-menu ">
    <app-left-menu></app-left-menu>
  </div>
  <div class="second-menu" >
    <app-second-menu (display)="onDisplay($event)" [expanded]=expanded ></app-second-menu>
  </div>
</div>

CSS

.menus{
  position: fixed;
}

问题scrollTop没有改变。当我执行console.log(this.doc.body.scrollTop)并滚动时,值为0且不会更改。

1 个答案:

答案 0 :(得分:1)

很可能身体不是滚动容器,HTML元素是

尝试document.documentElement.scrollTop

在浏览器中,document.documentElement是对根HTML元素的引用