【问题标题】:Scroll to class in angular 5以 Angular 5 滚动到班级
【发布时间】:2018-10-06 00:59:18
【问题描述】:

非常简单的问题,我如何才能滚动到有角度的课程,搜索了几个小时才能完成这项工作,真令人沮丧
我有一个日历组件,当我单击某一天时,该天的事件会在下方打开

使用纯 javascript 作为 id,但不是类

 const elmnt = document.getElementById('scrollto');
 elmnt.scrollIntoView(true);

我也有可用的 jQuery,但这根本不滚动

 if ($('.call-open').length > 0) {
      $('html, body').animate({
        scrollTop: $('.call-open').offset().top
      }, 2000);
    }

这个 .call-open 类是在我点击一天后添加的,也许这就是原因

我尝试了this 插件,但它什么也没做,即使是一个简单的示例按钮

我不能是唯一一个遇到这个问题的人,但我找不到任何可行的解决方案,对于像这样的简单事情来说,有些角度是一件很痛苦的事情

【问题讨论】:

  • 如果在点击事件之后添加元素或设置类,这听起来像是时间问题。在调用您的代码作为测试之前,使用 setTimeout() 引入一个小延迟。
  • @FatehMohamed 这是用于路由

标签: javascript jquery angular typescript scroll


【解决方案1】:

我使用以下代码解决了这个问题:

  constructor(private el: ElementRef) { }

  scrollToFirstInvalidControl() {
    const firstInvalidControl: HTMLElement = this.el.nativeElement.querySelector(
      "class-name"
    );
    if (!firstInvalidControl) return false
    window.scroll({
      top: this.getTopOffset(firstInvalidControl),
      left: 0,
      behavior: "smooth"
    });
  }

  getTopOffset(controlEl: HTMLElement): number {
    const labelOffset = 50;
    return controlEl.getBoundingClientRect().top + window.scrollY - labelOffset;
  }

【讨论】:

    【解决方案2】:

    用超时试试这个

    scroll(){
     setTimeout(() => {
        const classElement = document.getElementsByClassName('scrollTo');
        if(classElement.length > 0){
          classElement[0].scrollIntoView();
        }
     }
     }, 100);
    }
    

    【讨论】:

      【解决方案3】:

      这行得通,但该死的太丑了

       window.setTimeout(() => {
        if ($('.cal-open').length > 0) {
          $('html, body').animate({
            scrollTop: $('.cal-open').offset().top - 80
          }, 100);
        }
      }, (250));
      

      【讨论】:

      • 我需要 jQuery,我也需要它用于该页面中的其他内容,但如果没有 jQuery 的解决方案仍然会很好
      猜你喜欢
      • 2018-06-24
      • 1970-01-01
      • 2018-11-06
      • 2013-09-16
      • 1970-01-01
      • 2016-08-09
      • 2019-01-13
      • 1970-01-01
      • 2019-04-26
      相关资源
      最近更新 更多