我正在尝试在向下滚动时修复div;为此,我从下面的代码开始,我面临一些奇怪的问题,阻止我检测滚动行为。下面的代码console.log('bigger than 50')
在向下滚动时不会被打印。
为什么我无法检测到滚动事件?
@Component({
templateUrl: 'outlet.html',
selector: "app-layout-nav"
})
export class place {
constructor(@Inject(DOCUMENT) private document: Document) {}
@HostListener("window:scroll", [])
onWindowScroll() {
let number = this.document.body.scrollTop;
if (number > 50) {
console.log('bigger than 50')
this.navIsFixed = true;
} else if (this.navIsFixed && number < 10) {
console.log('lower than 50')
this.navIsFixed = false;
}
}
}
Outlet.html
<div>
<div id="wrap" [class.fixed]="navIsFixed">
This should be fixed when it reaches a certain level</div>
<div>The rest of the long page should show here</div>
</div>
答案 0 :(得分:3)
这可以帮助您检测元素或窗口上的滚动事件 https://github.com/anasAsh/ngx-scroll-event
使用NPM
npm install ngx-scroll-event --save
用纱线
yarn add ngx-scroll-event
导入ScrollEvent并将其添加到模块的imports数组中。
// app.module.ts
import { ScrollEventModule } from 'ngx-scroll-event';
@NgModule({
imports: [
...,
ScrollEventModule,
...,
]
})
export class AppModule { }
在模板中,您现在可以将detect-scroll
属性和(onScroll)
事件添加到任何元素。
您还可以添加[bottomOffest]
进行更改,当到达底部时警报为真,默认为100,该值应为以像素为单位的数字。
// app.awesome.component.ts
...
import { ScrollEvent } from 'ngx-scroll-event';
...
@Component({
...
template: `...
<div detect-scroll (onScroll)="handleScroll($event)" [bottomOffest]="200">
<div>Bla bla bla</div>
<div>Bla bla bla</div>
<div>Bla bla bla</div>
<div>Bla bla bla</div>
<div>Bla bla bla</div>
<div>Bla bla bla</div>
<div>Bla bla bla</div>
<div>Bla bla bla</div>
<div>Bla bla bla</div>
<div>
...`,
})
export class AwesomeComponent {
public handleScroll(event: ScrollEvent) {
console.log('scroll occurred', event.originalEvent);
if (event.isReachingBottom) {
console.log(`the user is reaching the bottom`);
}
if (event.isWindowEvent) {
console.log(`This event is hapening on Window not on an element.`);
}
}
}
答案 1 :(得分:2)
您可以将滚动事件绑定到容器:
<div class="container" (scroll)="onScroll($event)">
<div class="scrollable_content">
</div>
</div>
然后,在您的组件上:
onScroll(event){
const scrollTop = event.path[0].scrollTop;
}