【发布时间】:2019-11-13 17:34:23
【问题描述】:
滚动页面时我有粘性标题,它固定在页面顶部。当我单击标题页面中的菜单时,必须滚动到该特定 div。对于粘性标题,我使用 angular.for 滚动普通 java脚本 window.scroll()。但 window.scroll() 不能准确滚动。
//stickyheader.html
<div #stickyMenu [class.sticky]="sticky">
<div class="header">
<div class="navbar">
<ul>
<li><a>Home</a></li>
<li><a (click)="scrollTo('candidate')">Candidate</a></li>
<li><a (click)="scrollTo('client')">Client</a></li>
<li><a (click)="scrollTo('user')">User</a></li>
</ul>
</div>
</div>
</div>
//stickyhedaer.ts
import { Component, OnInit, AfterViewInit, ViewChild, ElementRef, HostListener } from '@angular/core';
import { TargetLocator } from 'selenium-webdriver';
@Component({
selector: 'app-sticky-header',
templateUrl: './sticky-header.component.html',
styleUrls: ['./sticky-header.component.css']
})
export class StickyHeaderComponent implements OnInit, AfterViewInit {
@ViewChild('stickyMenu') menuElement: ElementRef;
sticky: boolean;
elementPosition: any;
myElement: ElementRef;
constructor() {
this.sticky = false;
}
ngAfterViewInit() {
this.elementPosition = this.menuElement.nativeElement.offsetTop;
console.log(this.menuElement);
}
@HostListener('window:scroll', ['$event'])
handleScroll() {
const windowScroll = window.pageYOffset;
if (windowScroll >= this.elementPosition) {
this.sticky = true;
console.log(this.elementPosition + ' host listener scroll');
} else {
this.sticky = false;
}
}
scrollTo(id: any) {
console.log(id);
id = document.getElementById(id);
// id.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'start' });
const yCoordinate = id.getBoundingClientRect().top + window.pageYOffset;
const yOffset = 70;
window.scroll({
top: yCoordinate - yOffset,
behavior: 'smooth'
});
}
}
//app.component.html
<div>
<div class="content"></div>
<app-sticky-header></app-sticky-header>
<app-candidate></app-candidate>
<app-client></app-client>
<app-user></app-user>
<div class="content"></div>
</div>
【问题讨论】:
-
滚动到特定的 div 可以这样实现:stackoverflow.com/questions/46658522/…
-
这里还有一个滚动粘页的示例:joeljoseph.net/angular-sticky-header-on-scroll
-
@JoelJoseph 我试过 scrollIntoView(),同样的问题部分滚动到页面顶部并通过隐藏部分顶部元素与粘性标题重叠
标签: javascript css angular