angular - 如何将 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 有效,但这会将标题元素置于锚元素之上。我应该如何处理这个?
解决方案
好吧,不太确定使用 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);
推荐阅读
- c++ - 在这种特定情况下是否有必要重载运算符
- ruby - 使用 ruby 下载 .txt.gz
- c - 如何将 int64 位数据转换为 uint 32 位数据。C 运算符不得用于 64 位数据
- c++ - 在 C++ 中验证二进制输入
- python - 将列表的相应元素添加在一起
- ios - 生成新的 APNS 证书会使现有的活动证书无效
- android - 如何处理选定项目上的多个微调器?我不知道该怎么做
- python - 在取消方法 tkinter 之后
- elasticsearch - 为什么我的 Elasticseach API(_nodes/stats) 卡住了?
- python - 将 ['0','0 1 ','0 1 2','0 1 2 3'] 重新格式化为 ['0',['0','1'],...]