简体   繁体   English

滚动时的Angular 5粘滞菜单

[英]Angular 5 sticky menu when scroll

I would change menu position to fixed when menu reach top of page. 当菜单到达页面顶部时,我会将菜单位置更改为固定。 here's how I proceed. 这是我的工作方式。

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;
    }
  }

in HTML 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 CSS

.menus{
  position: fixed;
}

The problem is that scrollTop is not getting changed. 问题scrollTop没有改变。 when I do console.log(this.doc.body.scrollTop) and scroll, value is 0 and don't change. 当我做console.log(this.doc.body.scrollTop)并滚动时,值是0并且不会改变。

Most likely the body is not not the scroll container, the HTML element is 很可能主体不是滚动容器,HTML元素是

Try document.documentElement.scrollTop 试试document.documentElement.scrollTop

In browsers the document.documentElement is a reference to the root HTML element 在浏览器中, document.documentElement是对HTML根元素的引用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM