自动滑动的幻灯片组件通常由一个循环结构和一些指令组成。在 Angular 中,我们可以使用 ngFor 指令来循环列表,并且使用 setInterval 函数实现自动滑动的效果。
实现步骤如下:
import { Component } from '@angular/core';
@Component({ selector: 'app-slider', templateUrl: './slider.component.html', styleUrls: ['./slider.component.css'] }) export class SliderComponent { images = [ 'https://picsum.photos/id/1/200/300', 'https://picsum.photos/id/2/200/300', 'https://picsum.photos/id/3/200/300', 'https://picsum.photos/id/4/200/300' ];
currentIndex = 0; }
ngOnInit() { setInterval(() => { this.currentIndex = (this.currentIndex === this.images.length - 1) ? 0 : this.currentIndex + 1; }, 5000); }
.slider { position: relative; height: 600px; background-size: cover; background-position: center; animation-name: slide; animation-duration: 1s; animation-timing-function: ease-in-out; animation-iteration-count: infinite; }
.slider-content { position: absolute; top: 0;