普通页面中的写法
<a href="#id">跳转</a>
<div id="id">指定位置</div>
此方法在angular中是失效的,因为此写法跟路由冲突
解决方案一:(不推荐)
//html:
<a (click)="goDetail('id')">跳转</a>
<div id="id">指定位置</div>
//ts:
goDetail(id:string){
window.location.hash = '';
window.location.hash = name;
}
此方法在每次跳转的时候会导致hash刷新
解决方案二:
//html:
<a (click)="goDetail('id')">跳转</a>
<div id="id">指定位置</div>
//ts:
<!--引入-->
import { Router} from '@angular/router';
//...
constructor( private router: Router) { }
goDetail(id: string) {
const element = document.querySelector('#' + id);
if (element) { element.scrollIntoView(true); }
// 路由跳转
let _path = window.location.pathname;
this.router.navigate([`${_path}`], { fragment: `${id}` });
}
scrollIntoView() 方法让当前的元素滚动到浏览器窗口的可视区域内。参数true
,元素的顶端将和其所在滚动区的可视区域的顶端对齐,详见Element.scrollIntoView()
解决方案三:(此方法不会导致路由的变化)
//html:
<button (click)="goDistance1()">跳转到2</button>
<button (click)="goDistance2()">跳转到2</button>
<div #distannce1 style="width:500px;height:500px;background:green">123</div>
<div #distannce2 style="width:500px;height:500px;background:yellow">456</div>
//ts:
<!--引入-->
import { ViewChild, ElementRef } from '@angular/core';
//...
@ViewChild('distannce1') distannce1: ElementRef;
@ViewChild('distannce2') distannce2: ElementRef;
goDistance1(): void {
this.distannce1.nativeElement.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'start' });
}
goDistance2(): void {
this.distannce2.nativeElement.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'start' });
}