Angular中錨點的幾種方法

項目現象:在靜態頁面中往往需要點擊某個按鈕跳轉到當前頁面的某個地方

實現:

方法一:(不推薦)

頁面:

<button (click)="goDistance('distannce2')">跳轉到2</button>
<div id="distannce1" style="width:500px;height:500px;background:red"></div>
<div id="distannce2" style="width:500px;height:500px;background:yellow"></div>

控制:

goDistance(location: string): void {
    window.location.hash = ''; 
    window.location.hash = location;
}

方法二:

頁面:

<button (click)="goDistance()">跳轉到2</button>
<div #distannce1  style="width:500px;height:500px;background:red"></div>
<div #distannce2  style="width:500px;height:500px;background:yellow"></div>

控制:

<!--引入-->
import { ViewChild, ElementRef } from '@angular/core';

@ViewChild('distannce1') distannce1: ElementRef;
@ViewChild('distannce2') distannce2: ElementRef;

goDistance(): void {
    this.distannce2.nativeElement.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'start' });
}

方法三:(引入框架自帶的,舉個例子【Ant Design】)

<nz-anchor>
      <nz-link  nzHref="#distannce1" nzTitle="跳轉到1"></nz-link>
      <nz-link  nzHref="#distannce2" nzTitle="跳轉到2"></nz-link>
</nz-anchor>
<div id="distannce1" style="width:500px;height:500px;background:red"></div>
<div  id="distannce2" style="width:500px;height:500px;background:yellow"></div>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章