如何在没有插件的情况下平滑滚动到angular 4中的页面锚点? [英] How to smooth scroll to page anchor in angular 4 without plugins properly?
问题描述
我要实现的是单击并平滑滚动到我用井号定义的底部/指定的div区域,就像我认为应该是这样。
What I want to achieve is a click to and do a smooth scroll to bottom / specified div area which i define with hashtag just like i think it should be like this.
这是w3school示例中为JQuery编写的实时示例: https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_eff_animate_smoothscroll
here is the live example in the w3school example which is written for JQuery: https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_eff_animate_smoothscroll
什么我是从这个答案中偷看的:使用Hashtag路由到页面锚点的Angular2路由
What I do is peek from this answer: Angular2 Routing with Hashtag to page anchor
但是我不太明白答案,答案看起来像这样:
but i don't really understand the answer, the answer is looked like this :
这部分是HTML部分:
this part is HTML part :
<a [routerLink]="['somepath']" fragment="Test">Jump to 'Test' anchor </a>
在此之下,router.navigate应该放在哪里? component.ts对吗?但是我如何使用此功能?我应该实现(点击)吗?
and below this, the router.navigate is where should I put the code? component.ts right? but how do i access this function? should i implement (click)?
this._router.navigate( ['/somepath', id ], {fragment: 'test'});
在此以下,我得到它,它应该写在我的component.ts中:
and below this, i get it, which it should write in my component.ts :
** Add Below code to your component to scroll**
import {ActivatedRoute} from '@angular/router'; // <-- do not forget to import
private fragment: string;
constructor(private route: ActivatedRoute { }
ngOnInit() {
this.route.fragment.subscribe(fragment => { this.fragment = fragment; });
}
ngAfterViewInit(): void {
try {
document.querySelector('#' + this.fragment).scrollIntoView();
} catch (e) { }
}
什么是路径 是吗?我应该在我的routes.ts中添加一条路线,对吗?通常,我在这里添加一个新路径,例如:
what is the "somepath" mean? I should add a route in my routes.ts right? usually, i add a new path in here for example like this :
export const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'product', redirectTo: '/product' },
...homeRoutes,
...productRoutes
];
有人可以为我提供HTML,路由和组件的完整示例代码吗?
can anyone provide me with full example code in HTML, routes, and component?
推荐答案
我在寻找类似的解决方案,并尝试使用 ngx-scroll-to 包,发现它无法在最新版本的angular(angular 6+)中工作,因此决定研究其他选项并找到了解决方案使用浏览器的原生 scrollIntoView
,这似乎是迄今为止最好的解决方案
I was looking for a similar solution and tried to use the ngx-scroll-to package and found that its not working in latest version of angular (angular 6+) so decided to look into other option and found a solution which uses the browser's native scrollIntoView
and this seems to be the best solution so far
HTML代码:
<button (click)="scrollToElement(target)"></button>
<div #target>Your target</div>
Ts代码:
scrollToElement($element): void {
console.log($element);
$element.scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"});
}
这篇关于如何在没有插件的情况下平滑滚动到angular 4中的页面锚点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!