在模态框内部的动态内容改变时,我们需要手动更新滚动位置。具体方法是,在模态框打开时获取每个部分的偏移量,然后在每次内容变化时重新计算偏移量,并通过代码将滚动条移动到相应的位置。以下是一个示例代码:
在模态框组件中添加以下代码:
export class ModalComponent {
@ViewChild('scrollSection', { static: false }) scrollSection: ElementRef;
sectionOffsets: { [key: string]: number };
ngOnInit() {
this.sectionOffsets = {};
this.calculateSectionOffsets();
}
onContentChange() {
this.calculateSectionOffsets();
this.scrollToSection('section1');
}
private calculateSectionOffsets() {
const sections = ['section1', 'section2'];
sections.forEach((section) => {
const sectionElement = this.scrollSection.nativeElement.querySelector(`#${section}`);
this.sectionOffsets[section] = sectionElement.offsetTop;
});
}
private scrollToSection(section: string) {
window.scrollTo({
top: this.sectionOffsets[section] - 50, // 相应的便宜值,具体按需修改
behavior: 'smooth'
});
}
}
在模态框的 HTML 模板中,添加以下代码:
{{item.title}}
{{item.description}}
Section 2 content
在点击事件中,触发 onContentChange()
方法,该方法会重新计算偏移量并滚动到相应部分。
{{item.title}}