Angular中锚点的几种方法

  • Post author:
  • Post category:其他


项目现象:在静态页面中往往需要点击某个按钮跳转到当前页面的某个地方

实现:



方法一:(不推荐)

页面:

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



方法三


:如果在项目中引入了jquery那就可以直接用了

页面:

<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 * as $ from 'jquery';


goDistance(){
    let location= $('#' + this.routerinfo.snapshot.queryParams['distance']).offset().top;
    $('html, body').animate({ scrollTop: location }, 500);
}



方法四


:(引入框架自带的,举个例子【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>



版权声明:本文为qq_28004379原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。