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

查看:31
本文介绍了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 的 using div 和 section 来创建片段.但是,它不会将 div 或部分带到页面顶部.

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天全站免登陆