У меня есть липкий заголовок при прокрутке страницы, он фиксируется в верхней части страницы. Когда я нажимаю на меню на странице заголовка, необходимо прокрутить до этого конкретного div.Для липкого заголовка я использую angular.Для прокрутки обычной 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>