您可以使用 thisissoon 的 angular-scrollspy。我在我的 Angular 6 项目中使用过它,它工作得非常好。
以下是设置它的步骤
第 1 步:安装
npm i @thisissoon/{angular-scrollspy,angular-inviewport} --save
第 2 步:在 app.module.ts 中导入
import { InViewportModule, WindowRef } from '@thisissoon/angular-inviewport';
import { ScrollSpyModule } from '@thisissoon/angular-scrollspy';
// Provide window object for browser and a suitable replacement
// on other platforms
const getWindow = () => window;
const providers: Provider[] = [{ provide: WindowRef, useFactory: getWindow }];
@NgModule({
imports: [InViewportModule.forRoot(providers), ScrollSpyModule.forRoot()]
})
export class AppModule {}
第 3 步:将其添加到您的组件中(例如 navbar.component.ts)
<ul role="navigation" snScrollSpy id="foo">
<li><a snScrollSpyItem for="foo" href="#home">Home</a></li>
<li><a snScrollSpyItem for="foo" href="#about">About Us</a></li>
<li><a snScrollSpyItem for="foo" href="#team">Team</a></li>
<li><a snScrollSpyItem for="foo" href="#contact">Contact</a></li>
</ul>
<sn-scroll-spy-section id="home" for="foo">
Home Content
</sn-scroll-spy-section>
<sn-scroll-spy-section id="about" for="foo">
About Us Content
</sn-scroll-spy-section>
<sn-scroll-spy-section id="team" for="foo">
Team Content
</sn-scroll-spy-section>
<sn-scroll-spy-section id="contact" for="foo">
Contact Us content
</sn-scroll-spy-section>
PS:如果每个部分都在单独的(嵌套)组件内,这也是有效的。