【问题标题】:HTML <a> jump to a specific part of a page works from the second clickHTML <a> 从第二次点击开始跳转到页面的特定部分
【发布时间】:2021-03-30 19:56:16
【问题描述】:

我的登录页面中有以下 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 angular hyperlink


    【解决方案1】:

    试试这个

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

    【讨论】:

    • ? 您好,您的回答是 ? 有效,但我认为最好使用 ViewChild 之类的视图查询而不是 document.getElementById
    【解决方案2】:

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

    一种解决方法是使用模板变量并调用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 demo ??

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

    @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 demo ??

    检查此Passive Link in Angular 2 - equivalent 到 获取有关此问题的更多详细信息。

    【讨论】:

      猜你喜欢
      • 2020-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多