我有一个粘性导航栏,我想单击一个按钮并使该元素滚动到视图中。
这有效,但是它总是将标题放在我要滚动到视图中的元素的顶部。
html模板:
<div id="arrow-wrapper">
<div (click)="onArrowClick()" class="arrow-border">
<div class="arrow down"></div>
<div class="pulse"></div>
</div>
</div>
...
<div style="padding: 0 10px;">
<h1 #gearUp [ngClass]="routeAnimationsElements" class="heading">Gear Up!</h1>
Component.ts文件:
@ViewChild('gearUp') merchandiseCards: ElementRef;
onArrowClick(){
const targetELement = this.merchandiseCards.nativeElement as HTMLElement;
//targetELement.scrollIntoView({behavior: 'smooth'});
const elementPosition = targetELement.getBoundingClientRect().top;
const offsetPosition = elementPosition - 50;
window.scrollTo({
top: offsetPosition,
behavior: 'smooth'
})
targetELement.scrollBy({
top: offsetPosition,
behavior: 'smooth'
})
}
在上面的示例中,window.scrollTo或targetElement.scrollBy不起作用。仅targetElement.ScrollIntoView起作用,但这会将标头元素放在锚元素的顶部。我应该如何处理?
答案 0 :(得分:1)
不太确定使用document.getElemBy ...(用于重构等)访问其他elem是否是一个好主意,但是您可以执行以下操作:
const navigationRect = document.getElementById('sticky-header-id').getBoundingClientRect();
const padding = 30; // if needed
const offSet = navigationRect.top + navigationRect.height + padding;
const currElemRect = this.el.nativeElement.getBoundingClientRect();
const currentElemPosition = window.scrollY + currElemRect.top;
const scrollY = currentElemPosition - offSet;
window.scrollTo(0, scrollY);