85 lines
2.6 KiB
TypeScript
Executable File
85 lines
2.6 KiB
TypeScript
Executable File
// src/components/CarouselDemo.tsx
|
||
import * as React from "react";
|
||
import Autoplay from "embla-carousel-autoplay";//实现轮播图的自动播放功能
|
||
|
||
import { Card, CardContent } from "@/ui/card";
|
||
import {
|
||
Carousel,//主体
|
||
CarouselContent,//内容容器
|
||
CarouselItem,//单个轮播项
|
||
CarouselNext,
|
||
CarouselPrevious,
|
||
type CarouselApi,
|
||
} from "@/ui/carousel";
|
||
|
||
|
||
export function CarouselDemo() {
|
||
const [api, setApi] = React.useState<CarouselApi>();
|
||
const [current, setCurrent] = React.useState(0);
|
||
const [count, setCount] = React.useState(0);
|
||
|
||
const totalSlides = 6;
|
||
|
||
React.useEffect(() => {
|
||
if (!api) return;
|
||
|
||
setCount(api.scrollSnapList().length);
|
||
setCurrent(api.selectedScrollSnap());//获取当前选中的轮播项的索引
|
||
api.on("select", () => {
|
||
setCurrent(api.selectedScrollSnap());
|
||
});
|
||
}, [api]);//当api改变时,执行此函数 水平居中 循环 自动播放 回传状态
|
||
|
||
return (
|
||
<div className="relative w-full max-w-4xl mx-auto">
|
||
<Carousel
|
||
opts={{
|
||
loop: true,
|
||
}}
|
||
plugins={[
|
||
Autoplay({
|
||
delay: 3000,
|
||
stopOnInteraction: false,
|
||
}),
|
||
]}
|
||
setApi={setApi}
|
||
>
|
||
<CarouselContent className="h-full w-full">
|
||
{Array.from({ length: totalSlides }).map((_, index) => (
|
||
<CarouselItem key={index} className="w-full h-full">
|
||
<div className="p-1">
|
||
<Card>
|
||
<CardContent className="flex aspect-square items-center justify-center ">
|
||
<div
|
||
className="w-full h-full"
|
||
style={{
|
||
backgroundImage: "url('/public/images/header.png')",//背景图片可修改
|
||
backgroundSize: '100% 100%',
|
||
}}
|
||
>
|
||
</div>
|
||
</CardContent>
|
||
</Card>
|
||
</div>
|
||
</CarouselItem>
|
||
))}
|
||
</CarouselContent>
|
||
<CarouselPrevious className="absolute left-2 top-1/2 -translate-y-1/2 z-10" />
|
||
<CarouselNext className="absolute right-2 top-1/2 -translate-y-1/2 z-10" />
|
||
</Carousel>
|
||
|
||
{/* 分页指示器 - 右下角 */}
|
||
<div className="absolute bottom-4 right-4 flex gap-2 z-10">
|
||
{Array.from({ length: count }).map((_, index) => (
|
||
<button
|
||
key={index}
|
||
onClick={() => api?.scrollTo(index)}
|
||
className={`h-2 w-2 rounded-full transition-colors ${
|
||
index === current ? "bg-black" : "bg-black/50"
|
||
}`}
|
||
/>
|
||
))}
|
||
</div>
|
||
</div>
|
||
);
|
||
} |