【问题标题】:Angular 2+: how to jump to an anchor?Angular 2+:如何跳转到锚点?
【发布时间】:2018-04-10 03:33:03
【问题描述】:

我想使用 angular router 跳转/滚动到某个片段(散列)。 URL 正确生成为/#section5,但点击时没有任何反应。

经过大量搜索,我发现很多人(e.g.)有同样的问题,有一些解决方法,但没有合适的解决方案。我希望这是一个基本的核心功能。

以下代码不起作用:

<!-- Link --> 
<a routerLink="/" fragment="section5" routerLinkActive="active">Section 5</a>

<!-- Target -->
<div id="section5">Section 5 here</div>

有什么想法吗?

【问题讨论】:

标签: angular angular2-routing angular-routing


【解决方案1】:

你可以试试scrollIntoView,在你的组件的构造函数中添加下面的代码

router.events.subscribe(event => {
  if (event instanceof NavigationEnd) {
    const tree = router.parseUrl(router.url);
    if (tree.fragment) {
      const element = document.querySelector("#" + tree.fragment);
      if (element) { element.scrollIntoView(true); }
    }
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多