Sam*_*ami 3 css angular2-template angular
我有一个左侧边栏,位置固定.我想要实现的是,当我滚动大约50或60像素时,左侧边栏的位置应该更改为固定.
左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 {
}
Run Code Online (Sandbox Code Playgroud)
左sidebar.html
<div class="col-sm-2 left-nav">
</div>
Run Code Online (Sandbox Code Playgroud)
CSS
.left-nav {
position: absolute;
background: #424242;
height: 100%;
overflow: auto;
padding: 0;
z-index: 1;
}
Run Code Online (Sandbox Code Playgroud)
如何在滚动条上将左侧边栏的位置从绝对位置更改为固定位置?
我建议你使用@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;
}
}
Run Code Online (Sandbox Code Playgroud)
将.fixedcss 添加到scss文件,然后在模板中执行以下操作:
<div class="col-sm-2 left-nav" [class.fixed]="fixed">
</div>
Run Code Online (Sandbox Code Playgroud)