gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:50:45 25 4
gpt4 key购买 nike

这是一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com