要获取页面内元素的滚动位置,可以使用Angular中的ElementRef
和@HostListener
装饰器来实现。下面是一个示例代码,演示了如何获取元素的滚动位置。
首先,在组件中引入ElementRef
和@HostListener
:
import { Component, ElementRef, HostListener } from '@angular/core';
然后,在组件的构造函数中注入ElementRef
:
constructor(private elementRef: ElementRef) { }
接下来,使用@HostListener
装饰器来监听滚动事件,并在回调函数中获取滚动位置:
@HostListener('window:scroll', [])
onWindowScroll() {
const elementScrollPosition = this.elementRef.nativeElement.scrollTop;
console.log('Element scroll position:', elementScrollPosition);
}
在上述示例中,我们使用elementRef
来获取组件的原生元素,并使用scrollTop
属性来获取元素的滚动位置。你可以根据需要修改代码,以适应你的具体场景。
请注意,ElementRef
的使用需要引入@angular/core
模块,并确保在组件的构造函数中正确注入。