css - Angular 2 更改位置以固定在滚动条上

标签 css angular angular2-template

我有一个位置固定的左侧边栏。我想要实现的是,当我滚动大约 50 或 60 像素时,左侧边栏的位置应该更改为固定。

Left-sidebar.component.ts

import { Component } from '@angular/core';

@Component({
  moduleId: module.id,
  selector: 'left-sidebar',
  templateUrl: 'left-sidebar.html',
  styleUrls: ['left-sidebar.scss']
})
export class LeftSideBarComponent {
}

left-sidebar.html

<div class="col-sm-2 left-nav">

</div>

CSS

.left-nav {
  position: absolute;
  background: #424242;
  height: 100%;
  overflow: auto;
  padding: 0;
  z-index: 1;
}

如何在滚动时将左侧边栏的位置从绝对位置更改为固定位置?

最佳答案

我建议你使用 @HostListner 装饰器来监听滚动事件,就像这样:

 import { Inject, HostListener } from "@angular/core";
 import { DOCUMENT } from "@angular/platform-browser";

     @Component({
         moduleId: module.id,
         selector: 'left-sidebar',
         templateUrl: 'left-sidebar.html',
         styleUrls: ['left-sidebar.scss']
     })

  export class LeftSideBarComponent {
         public fixed: boolean = false; 

         constructor(@Inject(DOCUMENT) private doc: Document) {}

         @HostListener("window:scroll", [])
         onWindowScroll() {
            let num = this.doc.body.scrollTop;
            if ( num > 50 ) {
                this.fixed = true;
            }else if (this.fixed && num < 5) {
                this.fixed = false;
            }
         }

.fixed css 添加到您的 scss 文件中,然后在您的模板中执行以下操作:

<div class="col-sm-2 left-nav" [class.fixed]="fixed">

</div>

关于css - Angular 2 更改位置以固定在滚动条上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44144085/

相关文章:

html - 使用CSS定位div上方的div

javascript - Ionic 2 - 如何禁用滚动

html - IE11 嵌套 flexbox 问题与父表

angular - 如何在 Angular 5 中启用 "as syntax"创建自定义指令?

具有无限/#/in url的Angular 4路由

javascript - Angular2 : View updates when data changes, 但不适用于 ngif

angular - 我怎样才能拥有 Angular2 组件的动态 templateUrl?

html - 防止列表中的文本在图标元素符号下换行?

Angular 5 和 Sharepoint SPFX

angular - 为什么我们在 angular2 中使用 moduleId :module. id