如何在 Angular 2+ 中将滚动元素放入视口?

mr_*_*ond 4 html javascript css scroll angular

这是一个例子

有一个包含项目列表的组件:

class HomeComponent {
    text = 'foo';
    testObject = {fieldFirst:'foo'};
    itemList = [
        '1', 
        '2', 
        '3', 
        '4',
        '5',
        '6',
        '7',
        '8 This one should be scrolled into viewport',
        '9',
        '10',
        '11',
        '12',
      ];

    scrollToElement() {
        // Do scroll there
    }
}
Run Code Online (Sandbox Code Playgroud)

它的模板是:

 <button (click)="scrollToElement()">Scroll To 8th Element</button>
 <div class="wrapper">
    <li *ngFor="let item of itemList">{{item}}</li>
 </div>
Run Code Online (Sandbox Code Playgroud)

以及风格:

.wrapper {
    max-height: 300px;
    overflow-y: scroll;
}
Run Code Online (Sandbox Code Playgroud)

如何将第 8 个元素滚动到“wrapper”div 的视口中?

更新

这个答案并不能解决问题,因为问题不是如何使元素聚焦,问题是如何滚动到它。

Joh*_*ohn 5

您可以向列表元素添加唯一的 id,如下所示:

<li *ngFor="let item of itemList; let i = index;" id="list-item-{{i}}">{{item}}</li>
Run Code Online (Sandbox Code Playgroud)

然后你可以在click方法中找到该元素,并使用一个名为scrollIntoView();的方法;像这样。

scrollToElement() {
    document.getElementById("list-item-7").scrollIntoView();
}
Run Code Online (Sandbox Code Playgroud)

演示