【问题标题】:How to scroll an element in an Angular app into view with a sticky header?如何将 Angular 应用程序中的元素滚动到带有粘性标题的视图中?
【发布时间】:2019-09-19 01:20:05
【问题描述】:

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

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

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

【问题讨论】:

  • 你有没有试过弄乱你想看到的元素的 z-index 出现在顶部?
  • 我没有,但主要是因为我不想在标题顶部显示锚元素。我想显示在标题下方,就好像标题是正常文档流的一部分一样。
  • 这确实有效,事实上它按预期工作,但它不考虑粘性标题。

标签: angular


【解决方案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);

【讨论】:

    猜你喜欢
    • 2016-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-21
    相关资源
    最近更新 更多