【问题标题】:How to change the sticky header background color on scroll in angular 11如何在角度 11 中更改滚动时的粘性标题背景颜色
【发布时间】:2021-11-09 16:00:15
【问题描述】:

尝试将滚动到粘性标题时的背景颜色更改为无效。怎么做?当我滚动到正文的底部时,我需要更改标题背景颜色。怎么做?

app.component.html

<div class="header sticky">
</div>

app.component.css

 .sticky {
 position: -webkit-sticky;
 position: sticky;
 top: 0px;
 }

演示:https://stackblitz.com/edit/sticky-header-hyibz9?file=app%2Fheader%2Fheader.component.css

【问题讨论】:

    标签: css angular8 angular11


    【解决方案1】:

    您可以为此使用 ngClass 和 HostListener 来检查用户是否在按钮处滚动

    html

    <div class="header sticky" [ngClass]="isBottom ? 'bottom' : 'top'">
    </div>
    

    ts

    import { Component, OnInit, HostListener } from '@angular/core';
    
    @Component({
      selector: 'app-header',
      templateUrl: './header.component.html',
      styleUrls: ['./header.component.css']
    })
    export class HeaderComponent implements OnInit {
      isBottom: boolean;
    
      constructor() {}
    
      ngOnInit() {}
    
      @HostListener('window:scroll', [])
      onScroll(): void {
        if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
          this.isBottom = true;
        } else {
          this.isBottom = false;
        }
      }
    }
    

    css

    .sticky {
      position: -webkit-sticky;
      position: sticky;
      top: 0px;
    }
    
    .header {
      height: 50px;
    }
    
    .top {
      background-color: blue;
    }
    
    .bottom {
      background-color: yellow;
    }
    
    

    【讨论】:

    • 你可以使用添加类和删除类方法吗?有可能吗?
    • @Sansara,是的,但这取决于您设置的条件。如果需要,您可以使用多个 ngClass
    【解决方案2】:
    import { Component, OnInit, HostListener } from '@angular/core';
    
    @Component({
      selector: 'app-header',
      templateUrl: './header.component.html',
      styleUrls: ['./header.component.css']
    })
    export class HeaderComponent implements OnInit {
      isBottom: boolean;
    
      constructor() {}
    
      ngOnInit() {}
    
      @HostListener('window:scroll', [])
      onScroll(): void {
        if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
          this.isBottom = false;
        } else if (window.scrollY) {
          this.isBottom = false;
        } else  {
          this.isBottom = true;
        }
      }
    }
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2021-04-15
    • 2021-02-24
    • 1970-01-01
    • 2020-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-07
    相关资源
    最近更新 更多