Css 角度2将位置更改为固定在滚动上
我有一个位置固定的左侧边栏。我想要实现的是,当我滚动大约50或60像素时,左侧边栏的位置应该更改为固定 左侧边栏.component.tsCss 角度2将位置更改为固定在滚动上,css,angular,angular2-template,Css,Angular,Angular2 Template,我有一个位置固定的左侧边栏。我想要实现的是,当我滚动大约50或60像素时,左侧边栏的位置应该更改为固定 左侧边栏.component.ts import { Component } from '@angular/core'; @Component({ moduleId: module.id, selector: 'left-sidebar', templateUrl: 'left-sidebar.html', styleUrls: ['left-sidebar.scss'] }
import { Component } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'left-sidebar',
templateUrl: 'left-sidebar.html',
styleUrls: ['left-sidebar.scss']
})
export class LeftSideBarComponent {
}
.left-nav {
position: absolute;
background: #424242;
height: 100%;
overflow: auto;
padding: 0;
z-index: 1;
}
左侧边栏.html
<div class="col-sm-2 left-nav">
</div>
如何将左侧边栏的位置从绝对更改为固定在滚动上?我建议您使用
@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;
}
}
我使用的是Angular 4,但这个解决方案对我来说并不适用,我尝试了另一种方法,因为num在滚动时返回0。¯_(ツ)_/'' 我希望这也会对你有帮助
从“@angular/core”导入{Inject,HostListener};
@HostListener(“窗口:滚动,['$event']))
onWindowScroll($event:any){
让top=window.scrollY;
如果(顶部>30){
this.fixed=true;
控制台日志(顶部);
}else if(this.fixed&&top<5){
this.fixed=false;
控制台日志(顶部);
}
}
。已修复{
@扩展.bg白色;
位置:固定;
顶部:80px;
z指数:999;
}
切换下拉列表
行动-1
另一个动作
这里还有别的东西
谢谢我发现:被动事件侦听器更好(scroll jank),但@HostListener还不支持此功能。“document.scrollingElement.scrollTop”对我很有用。如果你不想自己编写此代码,你可以看看我的库,它解决了你的问题:
<div class="col-sm-2 left-nav" [class.fixed]="fixed">
</div>