旋转木马(Carousel)是一种常见的网页UI组件,用于在有限的空间内展示多个内容项(如图片、卡片等),通过自动或手动切换实现内容的轮播展示。
.carousel {
scroll-snap-type: x mandatory;
overflow-x: auto;
display: flex;
width: 100%;
scroll-behavior: smooth;
}
.carousel-item {
scroll-snap-align: start;
flex: 0 0 100%;
}
限制:这种方法只能实现手动滑动停止,无法控制自动轮播的停止。
class Carousel {
constructor(element, options = {}) {
this.element = element;
this.items = element.querySelectorAll('.carousel-item');
this.currentIndex = 0;
this.autoPlay = options.autoPlay || false;
this.stopAtEnd = options.stopAtEnd || false;
this.interval = options.interval || 3000;
this.timer = null;
this.init();
}
init() {
if (this.autoPlay) {
this.startAutoPlay();
}
// 添加导航按钮事件
this.addNavigationEvents();
}
startAutoPlay() {
this.timer = setInterval(() => {
if (this.stopAtEnd && this.currentIndex === this.items.length - 1) {
this.stopAutoPlay();
return;
}
this.next();
}, this.interval);
}
stopAutoPlay() {
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
}
next() {
this.currentIndex = (this.currentIndex + 1) % this.items.length;
this.updatePosition();
}
prev() {
this.currentIndex = (this.currentIndex - 1 + this.items.length) % this.items.length;
this.updatePosition();
}
updatePosition() {
const offset = -this.currentIndex * 100;
this.element.style.transform = `translateX(${offset}%)`;
}
addNavigationEvents() {
const nextBtn = this.element.parentElement.querySelector('.carousel-next');
const prevBtn = this.element.parentElement.querySelector('.carousel-prev');
if (nextBtn) {
nextBtn.addEventListener('click', () => {
this.stopAutoPlay();
this.next();
if (this.autoPlay) this.startAutoPlay();
});
}
if (prevBtn) {
prevBtn.addEventListener('click', () => {
this.stopAutoPlay();
this.prev();
if (this.autoPlay) this.startAutoPlay();
});
}
}
}
// 使用示例
document.addEventListener('DOMContentLoaded', () => {
const carouselElement = document.querySelector('.carousel');
new Carousel(carouselElement, {
autoPlay: true,
stopAtEnd: true,
interval: 3000
});
});
推荐使用Swiper.js实现:
import Swiper from 'swiper';
import 'swiper/css';
const swiper = new Swiper('.swiper', {
loop: false, // 禁用循环
autoplay: {
delay: 3000,
disableOnInteraction: false,
stopOnLastSlide: true // 到达最后一张时停止
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
});
loop: false
stopOnLastSlide: true
或自定义回调disableOnInteraction: false
没有搜到相关的文章