gpt4 book ai didi

javascript - 使用 Angular 2 在兄弟元素之间切换类

转载 作者:行者123 更新时间:2023-11-28 15:08:03 24 4
gpt4 key购买 nike

假设我有这段代码:

<div id="parent">
<div class="child">
<div class="child">
<div class="child">
</div>

我想要开始自动将active类添加到第一个子类中。之后,我希望每 X 秒切换到 active 类的下一个子级。 Angular 2 可以做到这一点吗?

最佳答案

Working Example

您可以使用如下模板动态地将类和项目添加到列表中:

<div id="parent">
<div *ngFor="let item of items; let i = index"
class="child" [class.active]="activeIndex === i">
{{item}}
</div>
</div>

与支撑组件:

export class AppComponent {
activeIndex = 0;
items = ['item 1', 'item 2', 'item 3']

ngOnInit() {
setInterval(_ => {
this.activeIndex++;
if (this.activeIndex >= this.items.length){
this.activeIndex = 0;
}
}, 500)
}
addItem() {
this.items.push('item ' + (this.items.length + 1));
}
}

关于javascript - 使用 Angular 2 在兄弟元素之间切换类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38014586/

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