Angular 8滚动到一个片段,不会将片段带到页面顶部 [英] Angular 8 scroll to a fragment, doesn't bring the fragment to the top of the page

查看:69
本文介绍了Angular 8滚动到一个片段,不会将片段带到页面顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个链接,通过单击链接,我想滚动到页面底部的一个片段.当我单击链接时,该片段正在工作,但没有将其带到页面顶部.

I have a link, by clicking on the link, I want to scroll to a fragment which is at the bottom of the page. When I click on the link, the fragment is working, but it doesn't bring it to the top of the page.

我尝试使用具有ID的div和section来创建片段.但是,它不会将div或section置于页面顶部.

I tried having the using div and section with an id to create the fragment. But, it doesn't bring the div or section to the top of the page.

我的应用程序路由模块中的代码是:

The code in my app routing module is:

 imports: [
    RouterModule.forRoot(routes, {
    //useHash: true,
    scrollPositionRestoration: 'enabled',
    onSameUrlNavigation: 'reload',
    anchorScrolling: 'enabled'
  })]

我的链接和片段的组件代码:

My component code for link and fragment:

<a [routerLink]="['/proposal']" fragment="dcn">{{ dcn }}</a>

<section id="dcn">
Some other html here
</section>

请注意,我已经尝试使用useHash:true,但是它似乎不起作用.我希望没有useHash的解决方案是正确的.

Note, I have tried using useHash:true, but it doesn't seem to work. I would prefer a solution without useHash to be true.

推荐答案

我使用这样的代码滚动到元素:

I use code like this to scroll to element:

HTML:

<button (click)="scroll(target)"></button>
<div #target>Your target</div>

TS:

scroll(el: HTMLElement) {
    el.scrollIntoView();
}

也许这对您有帮助.

记住::要滚动到元素,页面必须具有足够的内容才能生成滚动/滚动条,否则就没有滚动内容.

Remember: to page scroll to element, page must have sufficient contents do generate a scroll/scrollbar, otherwise does not have content to scroll.

这篇关于Angular 8滚动到一个片段,不会将片段带到页面顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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