角度 2 将位置更改为固定在滚动上 [英] angular 2 change position to fixed on scroll
问题描述
我有一个位置固定的左侧边栏.我想要实现的是,当我滚动大约 50 或 60 像素时,左侧边栏的位置应更改为固定.
Left-sidebar.component.ts
import { Component } from '@angular/core';@成分({模块 ID:module.id,选择器:'左侧边栏',templateUrl: 'left-sidebar.html',styleUrls: ['left-sidebar.scss']})导出类 LeftSideBarComponent {}
left-sidebar.html
css
.left-nav {位置:绝对;背景:#424242;高度:100%;溢出:自动;填充:0;z-索引:1;}
如何在滚动时将左侧边栏的位置从绝对位置更改为固定位置?
我建议你像这样使用 @HostListner
装饰器来监听滚动事件:
import { Inject, HostListener } from "@angular/core";从@angular/platform-browser"导入{文档};@成分({模块 ID:module.id,选择器:'左侧边栏',templateUrl: 'left-sidebar.html',styleUrls: ['left-sidebar.scss']})导出类 LeftSideBarComponent {公共固定:boolean = false;构造函数(@Inject(DOCUMENT)私有文档:文档){}@HostListener("window:scroll", [])onWindowScroll() {让 num = this.doc.body.scrollTop;如果(数量> 50){this.fixed = true;}else if (this.fixed && num <5) {this.fixed = false;}}
将 .fixed
css 添加到您的 scss 文件中,然后在您的模板中执行以下操作:
I have a left sidebar with position fixed. what I want to achieve is that when I scroll like about 50 or 60 pixel the position of the left sidebar should be changed to fixed.
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;
}
How to change position of left sidebar from absolute to fixed on scroll?
I suggest you make use of the @HostListner
decorator to listen to the scroll event just like this:
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;
}
}
add the .fixed
css to your scss file then in your template, you do the following:
<div class="col-sm-2 left-nav" [class.fixed]="fixed">
</div>
这篇关于角度 2 将位置更改为固定在滚动上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!