css 滚动事件在Angular-6中未触发

pinkon5k  于 2023-07-01  发布在  Angular
关注(0)|答案(2)|浏览(126)

我知道以前有人问过这个问题,但没有一个解决方案对我有效。
我正在开发Angular-6项目。我正在获取一个名为SectionComponent的组件中的Window-Scroll事件。

htmlbody标签样式:

html, body {
    overflow: auto;
    position: relative;
    margin: 0;
    height: 100%;
}

下面是组件的层次结构,说明如何管理组件。
我的AppComponent

HTML:

<div id="wrapper">
    <router-outlet></router-outlet>  
</div>

CSS:

#wrapper {
    width: 100vw;
    height: 100vh;
    position: relative;
    overflow: auto;
}

app.component.ts:

@HostListener('window:scroll', [])
  onWindowScroll() {
    console.log('scroll');
  }

AppComponent加载router-outlet标签中名为HomeComponent的组件。此HomeComponent使用is选择器加载SectionComponent

我的HomeComponent:

HTML:

<div class="home-wrapper">
  <div> 
    <!-- Some content more that window height -->
  </div>
  <app-section></app-section>
</div>

CSS:

.home-wrapper {
    position: relative;
    overflow-y: auto;
    height: 100%;
}

home.component.ts:

@HostListener('window:scroll', [])
  onWindowScroll() {
    console.log('scroll');
  }

我的SectionComponent

HTML:

<div class="section-wrapper">
  <!-- Some content more than window height -->
</div>

CSS:

.section-wrapper {
  position: relative;
  height: 2241px;
}

section.component.ts:

@HostListener('window:scroll', [])
  onWindowScroll() {
    console.log('scroll');
  }

我只想在SectionComponent中使用Window-Scroll。但没有任何组件触发事件。我做错了什么?

u5rb5r59

u5rb5r591#

import { ScrollDispatcher } from '@angular/cdk/scrolling';

  constructor(private scrollDispatcher: ScrollDispatcher) {    
    this.scrollDispatcher.scrolled().subscribe(x => console.log('I am scrolling'));
  }

在tempalte:

<div cdkScrollable>
  <div *ngFor="let one of manyToScrollThru">
    {{one}}
  </div>
</div>
6za6bjd0

6za6bjd02#

在您的SectionComponent中,在类声明之后使用

@HostListener('window:scroll', ['$event']) onScrollEvent($event){

var element =  document.getElementsByClassName('section-wrapper')[0];
var rect =   element.getBoundingClientRect();
 // the above code will return the CSS border-boxe associated with the element.
// so on scroll you will have readonly left, top, right, bottom, x, y, width, and height properties .
//on behalf of these properties you can manipulate the DOM section-wrapper div.

}

相关问题