【问题标题】:Angular hide div on scroll down, show div on show up向下滚动时隐藏 div,在显示时显示 div
【发布时间】:2021-06-04 16:37:08
【问题描述】:

我做了一些研究,刚刚看到窗口滚动事件。如何在 div 滚动事件中实现它?试了很多方法,还是不行。

如果 div(content) 向下滚动隐藏标题,如果 div(content) 向上滚动显示标题。

HTML

<header *ngIf="scroll">
    <app-toolbar (OpenDrawer)="OpenDrawer()"></app-toolbar>
    </header>
<div class="app-body">
    <content  scrollEvents="true" scrolling>
        <router-outlet></router-outlet>
    </content>
</div>

TS

import ...
...
enum VisibilityState {
  Visible = 'visible',
  Hidden = 'hidden'
}

enum Direction {
  Up = 'Up',
  Down = 'Down'
}

@Component
...
export class TabLayout implements OnInit {
...
    @Input() stickyHeader = false;
    scroll() {
        const scroll$ = fromEvent(this.el.nativeElement, 'scroll').pipe(
          throttleTime(10),
          map(() => this.el.nativeElement.pageYOffset),
          pairwise(),
          map(([y1, y2]): Direction => (y2 < y1 ? Direction.Up : Direction.Down)),
          distinctUntilChanged(),
          share()
        );

        const scrollUp$ = scroll$.pipe(
          filter(direction => direction === Direction.Up)
        );

        const scrollDown = scroll$.pipe(
          filter(direction => direction === Direction.Down)
        );

        scrollUp$.subscribe(() => (this.isVisible = true));
        scrollDown.subscribe(() => (this.isVisible = false));
    }
}

【问题讨论】:

    标签: angular ionic-framework angular11


    【解决方案1】:

    您可以像在普通网站中那样实现这一点,只需要对 DOM 元素的引用,并且可以使用 @ViewChild 来实现:

    HTML:

    <div #scroller></div>
    
    <div *ngIf="displayDiv"></div>    // Element you want to hide on scroll
    

    TS (Javascript)

    import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
    
    export class MyComponent implements OnInit {
    
      @ViewChild('scroller')
      scroller: ElementRef;
    
      displayDiv = true;
    
      ngOnInit() {
      
         this.scroller.nativeElement.onscroll = () => {
    
             let top = this.scroller.nativeElement.scrollTop;
    
             if (top > 0) {               // We scrolled down
                 this.displayDiv = false;
             }
             else {
                 this.displayDiv = true;
             }
    
         }
    
      }
    }
    
    

    【讨论】:

    • 您好,是向上滚动显示,向下滚动隐藏而不是滚动到顶部显示。
    猜你喜欢
    • 2014-05-26
    • 2012-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多