标签的引用问题<a>通过id#element引用元素

问题描述 投票:0回答:1

请帮忙解决这个问题,

我的 HTML 文档中有一个带有 ID 的标签:

the tag with id

问题是,当我使用引用调用时,屏幕不会移动。参考调用:

我尝试了两种方法,都不起作用:

方式1:

using router link and fragment

方式2:

using only href with #id

请帮忙

我尝试两种方式

我期待别人以其他方式

angular dom tags href
1个回答
0
投票

看到导入RouterModule.forRoot时,可以添加一个“routerOptions”

在此功能中您可以包含 routerOptions

const routerOptions: ExtraOptions = {
  scrollPositionRestoration: 'enabled',
  anchorScrolling: 'enabled', //<--this makes the trick
  scrollOffset: [0, 64], //<--this is for not just in the anchor
};

const routes: Routes = [ ...]

@NgModule({
  imports: [CommonModule, RouterModule.forRoot(routes, routerOptions)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

注意:来源并注明此链接,您可以使订阅 router.events 的锚点的移动更加顺畅,而不是使用 routerOptions

export class AppModule { 
  constructor(router: Router, viewportScroller: ViewportScroller) {
    viewportScroller.setOffset([0, 50]);
    router.events.pipe(filter(e => e instanceof Scroll)).subscribe((e: Scroll) => {
      if (e.anchor) {
        // anchor navigation
        /* setTimeout is the core line to solve the solution */
        setTimeout(() => {
          viewportScroller.scrollToAnchor(e.anchor);
        })
      } else if (e.position) {
        // backward navigation
        viewportScroller.scrollToPosition(e.position);
      } else {
        // forward navigation
        viewportScroller.scrollToPosition([0, 0]);
      }
    });
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.