javascript - 如何在 Angular 2+ 中将滚动元素制作成视口(viewport)?

标签 javascript html css angular scroll

这是一个 example

里面有元素列表的组件:

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
    }
}

它的模板:

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

还有样式:

.wrapper {
    max-height: 300px;
    overflow-y: scroll;
}

如何将第 8 个元素滚动到“包装”div 的视口(viewport)中?

Update

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

最佳答案

您可以像这样向您的列表元素添加一个唯一的 id:

<li *ngFor="let item of itemList; let i = index;" id="list-item-{{i}}">{{item}}</li>

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

scrollToElement() {
    document.getElementById("list-item-7").scrollIntoView();
}

Demo

关于javascript - 如何在 Angular 2+ 中将滚动元素制作成视口(viewport)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58293531/

相关文章:

php - jQuery 模态确认

html - 导航下拉内容未在屏幕上正确显示

css - 为什么隐藏的内容会影响布局,即使在父级上隐藏了溢出?

javascript - 我可以用 JavaScript 编写 Selenium 测试吗?

javascript - html5 需要验证在浏览器上运行良好,但在 phonegap 应用程序上运行良好

javascript - 向博客类型网站添加帖子的方法

javascript - execCommand 标题不起作用

html - 水平和垂直居中 div 元素

css - 如何创建在断点处转到内容下方的响应式侧边栏?

CSS - 向左浮动和定位元素