繁体   English   中英

HTML<a>从第二次点击跳转到页面的特定部分</a>

[英]HTML <a> jump to a specific part of a page works from the second click

我的登录页面中有以下 HTML 代码

<div class="col-12 text-center mt-4 mb-4">
   <a class="btn know-more-btn text" href="#billing">Tell Me More</a>
</div>

<div id="billing" class="billing-section">
   //show some billing options
</div>

当第一次单击btn know-more-btn时,屏幕闪烁,仅从第二次单击它“跳转”到页面上的正确位置(计费部分)没有任何反应 不知道为什么会发生这种情况

还有一种方法可以将“跳转”转换为快速滚动到该部分的模拟

尝试这个

html

<div class="col-12 text-center mt-4 mb-4" (click)="toSec()">
   <a class="btn know-more-btn text">Tell Me More</a>
</div>

ts

toSec() {
  document.getElementById("billing").scrollIntoView();
}

平滑滚动将其添加到主样式文件

css

html {
  scroll-behavior: smooth;
}

这不适用于路由器<a href="#billing">Tell Me More</a> ,它将触发路由器重定向到某个页面或重新加载页面。

所以一种解决方法是使用模板变量并调用scrollIntoView方法来应用滚动。

<div class="basic c-pointer col-12 text-center mt-4 mb-4">
   <a class="btn know-more-btn text" 
    (click)="billingElm.scrollIntoView({behavior: 'smooth'})" >
      Tell Me More 👇
    </a>
</div>

<div #billingElm class="billing-section">
   //show some billing options
</div>

stackblitz 演示

为了可重用性,这是指令方式

@Directive({
  selector: '[scrollTo]'
})
export class ScrollToDirective {

  @Input('scrollTo') elm:HTMLElement;

  @HostListener('click') onClick(){
    if(this.elm){
      this.elm.scrollIntoView({behavior:'smooth'});
    }
  }
}

模板

<div class="col-12 text-center mt-4 mb-4">
   <a class="btn know-more-btn text" [scrollTo]="billingElm" >Tell Me More 👇</a>
</div>

<div #billingElm class="billing-section">
   //show some billing options
</div>

stackblitz 演示

检查Angular 2 中的这个被动链接 - 相当于获得有关此问题的更多详细信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM