在Angular 7+中,可以通过使用ElementRef和ViewChild来获取和设置div元素的滚动位置。以下是一个示例解决方法:
在组件的HTML模板中,添加一个带有滚动条的div元素,并为其添加一个标识符。
在组件的typescript文件中,引入ElementRef和ViewChild,并添加以下代码:
import { Component, ElementRef, ViewChild } from '@angular/core';
@Component({
selector: 'app-scroll-example',
templateUrl: './scroll-example.component.html',
styleUrls: ['./scroll-example.component.css']
})
export class ScrollExampleComponent {
@ViewChild('scrollContainer', {static: false}) scrollContainer: ElementRef;
getScrollPosition() {
// 获取滚动位置
const scrollPosition = this.scrollContainer.nativeElement.scrollTop;
console.log(scrollPosition);
}
setScrollPosition() {
// 设置滚动位置
this.scrollContainer.nativeElement.scrollTop = 100;
}
}
在上述代码中,@ViewChild('scrollContainer')装饰器用于获取带有标识符“scrollContainer”的div元素的引用。然后,可以使用nativeElement属性来访问该元素,并通过scrollTop属性获取或设置滚动位置。
在组件的HTML模板中,你可以使用按钮或其他触发事件的元素来调用getScrollPosition()和setScrollPosition()方法。
这样,当你点击“获取滚动位置”按钮时,控制台将打印出滚动位置;当你点击“设置滚动位置”按钮时,div元素将滚动到位置100。