gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:06:58 25 4
gpt4 key购买 nike

我有一个位置固定的左侧边栏。我想要实现的是,当我滚动大约 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com