滚动至锚点不起作用 [英] Scroll to anchor not working

查看:68
本文介绍了滚动至锚点不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用以下语法滚动到锚链接.

Trying to scroll to an anchor link using the following syntax.

<a [routerLink]="['./']" fragment="test">Testing</a>

锚节点看起来像这样

<div id="test">

单击时,浏览器地址栏显示#test片段,但不会自动滚动.知道为什么它不滚动吗?

When clicked the browser address bar shows the #test fragment but the automatic scrolling does not occur. Any idea why it does not scroll?

推荐答案

基于 @vsavkin 解决方法,并利用片段作为可观察的对象(使用"@angular/core": "^2.3.1")提供了优势:

Based on @vsavkin workaround and taking advantage that fragments are provided as an observable (using "@angular/core": "^2.3.1"):

class MyAppComponent implements OnInit{

  constructor(private route: ActivatedRoute) { }

  ngOnInit() {
    this.route.fragment.subscribe(f => {
      const element = document.querySelector("#" + f)
      if (element) element.scrollIntoView()
    })
  }
}

这篇关于滚动至锚点不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆