Angular实现锚点

3,218 阅读1分钟
普通页面中的写法  

<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);

// scrollIntoView() 方法让当前的元素滚动到浏览器窗口的可视区域内,true:顶端对齐

if (element) { element.scrollIntoView(true); } 

// 路由跳转

 let _path = window.location.pathname;

 this.router.navigate([`${_path}`], { fragment: `${id}` }); } 


解决方案三:(此方法不会导致路由的变化)

 //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'
     }); 
}