角度2更改位置以固定在滚动条上 [英] angular 2 change position to fixed on scroll

查看:41
本文介绍了角度2更改位置以固定在滚动条上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

我建议您使用@HostListner装饰器来监听滚动事件,如下所示:

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;
            }
         }

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆