【问题标题】:Scroll 10 px top to particular div向上滚动 10 px 到特定的 div
【发布时间】:2019-07-24 22:06:23
【问题描述】:

我已经编写了下面的代码来滚动顶部到特定的 div,它工作正常。 但我想在特定字段上再滚动 10 像素。单击提交按钮时,它会滚动到错误块,但看不到完整的文件。我们如何滚动到目标类。

public scrollIntoError(formId: string): void {
  setTimeout(() => {
    const selector = "#" + formId + " .error-class";
    const firstElementWithError = document.querySelector(selector);
    this.scrollToError(firstElementWithError);
  }, NumberConstants.HUNDRED);
} 

public scrollToError(el: Element): void {
  if (el) {
    el.scrollIntoView({behavior: "smooth"});
  }
} 

以上代码运行良好,但我想在所选类上再滚动前 10 像素。

编辑

页面有滚动条,只有中间有表单的部分有滚动条。

【问题讨论】:

  • 您是否查看过alignToTopscrollIntoViewOptions 可能正在设置类似blockinline 的选项可能会为您提供最接近的结果
  • 是的 @JoelJoseph el.scrollIntoView({behavior: "smooth", block: "center"});这对我有用,谢谢

标签: javascript angular


【解决方案1】:

这将平滑滚动一次:

public scrollToError(el: Element): void {
    if (el) {
        el.scroll({
            top: el.scrollTop - 10, 
            left: 0,
            behavior: 'smooth'
        });
    }
} 

【讨论】:

    【解决方案2】:

    您可以为此再执行一条语句:

    public scrollToError(el: Element): void {
      if (el) {
        el.scrollIntoView({behavior: "smooth"});
        el.scrollBy(0, 10);
      }
    } 
    

    【讨论】:

    • 很可能scrollBy 将在scrollIntoView 完成滚动之前开始工作
    • 我没有浏览器滚动条,这是带有滚动条的中间部分表单。主页有滚动条。我认为 window.scroll 在这种情况下不起作用
    • 好的,我已经编辑了评论,应该是el.scollBy,而不是window.scrollBy
    猜你喜欢
    • 2017-02-01
    • 2014-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多