要追踪一个div中另一个div的滚动位置,可以使用Angular的ViewChild和HostListener装饰器来实现。下面是一个示例代码:
HTML模板:
组件代码:
import { Component, ElementRef, HostListener, ViewChild } from '@angular/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent {
@ViewChild('parentDiv') parentDiv: ElementRef;
@ViewChild('childDiv') childDiv: ElementRef;
@HostListener('scroll', ['$event'])
onScroll(event: any) {
const parentScrollTop = this.parentDiv.nativeElement.scrollTop;
const childScrollTop = this.childDiv.nativeElement.scrollTop;
console.log('Parent Scroll Top: ', parentScrollTop);
console.log('Child Scroll Top: ', childScrollTop);
}
}
在这个示例中,我们使用ViewChild装饰器来获取父div和子div的引用。然后,我们使用HostListener装饰器在组件上监听scroll事件。当滚动事件发生时,我们通过nativeElement属性获取div的scrollTop属性,并打印出来。
你可以将这个示例代码添加到你的Angular项目中,并根据需要进行修改。