普通頁面中的寫法
<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' });
}