滚动页面时我有粘性标题,它固定在页面顶部。当我单击标题页面上的菜单时,必须滚动到该特定的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>
答案 0 :(得分:1)
我做了一个与您的查询有关的stackblitz示例。在该标头中,粘贴并滚动到该部分可正常工作。我没有添加多个组件。取而代之的是,我在
标记中添加了文本,并为该部分赋予了相同的ID。