首页 > 解决方案 > 如何将 Angular 应用程序中的元素滚动到带有粘性标题的视图中?

问题描述

我有一个粘性导航栏,我想单击一个按钮并让该元素滚动到视图中。

这可行,但是它总是将标题放在我试图滚动到视图中的元素的顶部。

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>

组件.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 有效,但这会将标题元素置于锚元素之上。我应该如何处理这个?

标签: angular

解决方案


好吧,不太确定使用 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);

推荐阅读