【问题标题】:Scroll to the center of a DIV element - Angular 7滚动到 DIV 元素的中心 - Angular 7
【发布时间】:2019-09-25 06:09:25
【问题描述】:

当某个函数被触发时,我想滚动到元素的 Y 和 X 中心。 我的 HTML 看起来像这样(我想滚动到#viewport 的中间):

 </div>
      <div #viewport class="document-view-port">
          <div #viewBox></div>
 </div>

在我的 TS 中,我正在导入这样的元素(这里我尝试找到 y 中心):

  @ViewChild('viewBox') viewBox: ElementRef;
  @ViewChild('viewport') viewport: ElementRef; 

我尝试提取此中心点进行滚动的最后一种方法是:

  zoomIn() {
    const elementRect = this.viewport.nativeElement.getBoundingClientRect();
    const absoluteElementTop = elementRect.top + window.pageYOffset;
    const middle = absoluteElementTop - (elementRect.height / 2);  
    this.viewport.nativeElement.scrollTo(0, middle)
  }

我做不到,任何帮助将不胜感激

[编辑]

方法 scrollIntoView() 在我的代码中没有做任何事情。我想在不使用任何预定义函数的情况下找到这些坐标并滚动

【问题讨论】:

  • @JamieRees。它没有帮助。 scrollIntoView() 在我的情况下根本不做任何事情。
  • 你应该使用window.scrollTo(0, middle);进行滚动

标签: javascript html css angular


【解决方案1】:

你应该使用window.scrollTo(x, y)来实现滚动:

zoomIn() {
    const elementRect = this.viewport.nativeElement.getBoundingClientRect();
    const absoluteElementTop = elementRect.top + window.pageYOffset;
    const middle = absoluteElementTop - (elementRect.height / 2);  
    window.scrollTo(0, middle); // have a window object reference in your component
  }

【讨论】:

  • 感谢您的帮助,我尝试了代码,但它没有做任何事情middle = -225
  • @Igor.ro 你对 -225 有什么期望?那永远行不通。尝试调试为什么它是负值。该值必须为正才能起作用。
猜你喜欢
  • 2020-06-23
  • 1970-01-01
  • 2016-10-28
  • 1970-01-01
  • 2014-11-12
  • 2019-12-25
  • 2020-03-09
  • 1970-01-01
  • 2010-10-12
相关资源
最近更新 更多