在Angular 4中单击时滚动到元素

74 html javascript typescript angular

我希望能够在按下按钮时滚动到目标.我在想这样的事情.

<button (click)="scroll(#target)">Button</button>
Run Code Online (Sandbox Code Playgroud)

在我的component.ts中有一个类似的方法.

scroll(element) {
    window.scrollTo(element.yPosition)
}
Run Code Online (Sandbox Code Playgroud)

我知道上面的代码无效,只是为了表明我的想法.我刚刚开始学习Angular 4而没有以前的Angular经验.我一直在寻找类似的东西,但所有的例子都在AngularJs中,与Angular 4不同

Fra*_*ica 114

你可以这样做:

<button (click)="scroll(target)"></button>
<div #target>Your target</div>
Run Code Online (Sandbox Code Playgroud)

然后在你的组件中:

scroll(el: HTMLElement) {
    el.scrollIntoView();
}
Run Code Online (Sandbox Code Playgroud)

编辑:我看到评论声明由于元素未定义,这不再有效.我在Angular 7中创建了一个StackBlitz示例,它仍然有效.有人可以提供一个不起作用的例子吗?

  • 这不起作用,el由于某种原因未定义 (7认同)
  • @N15M0_jk 是的,还有一个对象可以与其他选项一起传入,具体取决于您的需要。https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView (2认同)
  • @Anthony它允许您引用要传递给组件上的“scroll”函数的元素。请注意,单击事件调用“scroll(target)”。如果您想从组件内部访问该元素而不必传入该元素,则可以使用“@ViewChild”。 (2认同)
  • 现在对我来说很好。但是在我犯了一个愚蠢的错误并使用`id =“ target”`而不是`#target`之前,它给了我“ el is undefined error”! (2认同)
  • 我相信如果带有“#target”的元素位于“*ngIf”内,则会发生未定义的错误,但如果您在@abbastec的链接中使用“@ViewChild”方法,它应该可以工作 (2认同)

LH7*_*LH7 32

这是我用角度4做的方式.

模板

<div class="col-xs-12 col-md-3">
  <h2>Categories</h2>
  <div class="cat-list-body">
    <div class="cat-item" *ngFor="let cat of web.menu | async">
      <label (click)="scroll('cat-'+cat.category_id)">{{cat.category_name}}</label>
    </div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

将此函数添加到Component.

scroll(id) {
  console.log(`scrolling to ${id}`);
  let el = document.getElementById(id);
  el.scrollIntoView();
}
Run Code Online (Sandbox Code Playgroud)

  • 您尚未在模板中设置 elementRefs 或 HTML id。您要滚动到的 'cat-'+cat.category_id 元素究竟在哪里? (6认同)

Jon*_*Jon 31

实际上有一种纯粹的javascript方法可以在不使用setTimeout或者使用requestAnimationFramejQuery的情况下完成此任务.

简而言之,在scrollView中找到要滚​​动到的元素,然后使用scrollIntoView.

el.scrollIntoView({behavior:"smooth"});

这是一个傻瓜.

  • 答案有2种不同的方式:1.这是动画平滑滚动,而不是跳跃。2.此答案不会滚动窗口,而是在窗口内移动滚动视图。例如,如果您在窗口中有一个水平滚动视图。查看plunkr的示例。 (2认同)

小智 17

乔恩有正确的答案,这适用于我的角度5和6项目.

如果我想点击以平滑地从导航栏滚动到页脚:

<button (click)="scrollTo('.footer')">ScrolltoFooter</button>
<footer class="footer">some code</footer>

scrollTo(className: string):void {
   const elementList = document.querySelectorAll('.' + className);
   const element = elementList[0] as HTMLElement;
   element.scrollIntoView({ behavior: 'smooth' });
}
Run Code Online (Sandbox Code Playgroud)

因为我想从页脚回滚到页眉,我创建了一个这个函数所在的服务,并将其注入到导航栏和页脚组件中,并在需要时传入"页眉"或"页脚".只记得实际给组件声明使用的类名:

<app-footer class="footer"></app-footer>
Run Code Online (Sandbox Code Playgroud)


小智 17

在角度7完美的作品

的HTML

<button (click)="scroll(target)">Click to scroll</button>
<div #target>Your target</div>
Run Code Online (Sandbox Code Playgroud)

在组件中

  scroll(el: HTMLElement) {
    el.scrollIntoView({behavior: 'smooth'});
  }
Run Code Online (Sandbox Code Playgroud)

  • {行为:'平稳'}的奖励 (7认同)
  • 如果在按钮之后定义了“#target”,则这将不起作用,例如,如果您有浮动标题,则这是相关的...... (3认同)

Nic*_*cky 16

这个派对的时间已经很晚了,但是我已经为Angular 4+编写了一个插件.它涵盖了您可能遇到的其他问题,例如服务器端渲染.您还可以动画滚动到您的喜好.完全披露,我是作者.

NPM:@ nicky-lenaers/ngx-scroll-to

GitHub:@ nicky-lenaers/ngx-scroll-to

希望这可以帮助你!


Ife*_*yan 15

您可以使用下面的代码块滚动到视图上的任何元素引用。请注意,目标(elementref id ) 可以位于任何有效的 html 标签上。

在视图上(html 文件)

<div id="target"> </div>
<button (click)="scroll()">Button</button>
 

  
Run Code Online (Sandbox Code Playgroud)

.ts文件上,

scroll() {
   document.querySelector('#target').scrollIntoView({ behavior: 'smooth', block: 'center' });
}
Run Code Online (Sandbox Code Playgroud)


And*_*iol 8

您可以通过使用对 angular DOM 元素的引用来实现这一点,如下所示:

这是stackblitz中的例子

组件模板:

<div class="other-content">
      Other content
      <button (click)="element.scrollIntoView({ behavior: 'smooth', block: 'center' })">
        Click to scroll
      </button>
    </div>
    <div id="content" #element>
      Some text to scroll
</div>
Run Code Online (Sandbox Code Playgroud)


Sch*_*apz 6

在Angular中执行此操作的另一种方法是:

标记:

<textarea #inputMessage></textarea>
Run Code Online (Sandbox Code Playgroud)

添加ViewChild()属性:

@ViewChild('inputMessage')
inputMessageRef: ElementRef;
Run Code Online (Sandbox Code Playgroud)

使用scrollIntoView()函数滚动到组件内部所需的任何位置:

this.inputMessageRef.nativeElement.scrollIntoView();
Run Code Online (Sandbox Code Playgroud)


小智 5

在角度,您可以使用ViewChild和ElementRef:给您的html元素一个参考

<div #myDiv > 
Run Code Online (Sandbox Code Playgroud)

在组件内部:

import { ViewChild, ElementRef } from '@angular/core';
@ViewChild('myDiv') myDivRef: ElementRef;
Run Code Online (Sandbox Code Playgroud)

您可以使用this.myDivRef.nativeElement进入您的元素