Carousel
用原生滚动、键盘操作和可选的自动轮播逐页浏览幻灯片。
用 Carousel 一次显示一屏幻灯片,比如产品照片或精选故事。它使用原生滚动,所以滑动和触控板都能用,Previous 和 Next 按钮用来翻页。
import {
Carousel,
CarouselContent,
CarouselItem,
CarouselNext,
CarouselPrevious,
CarouselViewport,
} from "@ui-sdk/solid/carousel"
import { For } from "solid-js"
const slides = [1, 2, 3, 4, 5]
function Example() {
return (
<Carousel aria-label="Featured">
<div data-slot="row">
<CarouselPrevious aria-label="Previous slide">
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="m15 18-6-6 6-6" />
</svg>
</CarouselPrevious>
<CarouselViewport>
<CarouselContent>
<For each={slides}>
{(slide) => (
<CarouselItem>
<div data-slot="tile">{slide}</div>
</CarouselItem>
)}
</For>
</CarouselContent>
</CarouselViewport>
<CarouselNext aria-label="Next slide">
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="m9 18 6-6-6-6" />
</svg>
</CarouselNext>
</div>
</Carousel>
)
}
export { Example }安装
npm install @ui-sdk/solid @ui-sdk/core组合
用下面的组合构建 Carousel:
Carousel
├── CarouselViewport
│ └── CarouselContent
│ ├── CarouselItem
│ └── CarouselItem
├── CarouselPrevious
└── CarouselNext把幻灯片放进视口,然后加上你需要的控件。
视口是滚动的窗口,内容则是里面那一排幻灯片,一个 flex 行(垂直时是列)。用 aria-label 给轮播命名,比如“Featured products”;给 Previous、Next、指示器和播放切换按钮提供文字,当它们只放图标时提供 aria-label。
用法
导入部件并把它们组合起来:
import {
Carousel,
CarouselViewport,
CarouselContent,
CarouselItem,
CarouselPrevious,
CarouselNext,
} from "@ui-sdk/solid/carousel"
function FeaturedSlides() {
return (
<Carousel aria-label="Featured">
<CarouselViewport>
<CarouselContent>
<CarouselItem>First slide</CarouselItem>
<CarouselItem>Second slide</CarouselItem>
</CarouselContent>
</CarouselViewport>
<CarouselPrevious>Previous</CarouselPrevious>
<CarouselNext>Next</CarouselNext>
</Carousel>
)
}
export { FeaturedSlides }垂直
orientation="vertical" 让幻灯片上下滚动。给视口一个高度。上下方向键用来翻页,而不是左右方向键。
import {
Carousel,
CarouselContent,
CarouselItem,
CarouselNext,
CarouselPrevious,
CarouselViewport,
} from "@ui-sdk/solid/carousel"
import { For } from "solid-js"
const slides = [1, 2, 3, 4, 5]
function Example() {
return (
<Carousel aria-label="Featured" orientation="vertical">
<CarouselViewport>
<CarouselContent>
<For each={slides}>
{(slide) => (
<CarouselItem>
<div data-slot="tile">{slide}</div>
</CarouselItem>
)}
</For>
</CarouselContent>
</CarouselViewport>
<div data-slot="row">
<CarouselPrevious aria-label="Previous slide">
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="m18 15-6-6-6 6" />
</svg>
</CarouselPrevious>
<CarouselNext aria-label="Next slide">
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="m6 9 6 6 6-6" />
</svg>
</CarouselNext>
</div>
</Carousel>
)
}
export { Example }循环
loop 让幻灯片首尾相接。在最后一页按 Next 会到第一页,而第一页排在最后一张之后;从第一页往回滑动、拖动或滚轮滚动,会到达最后一页,全程都是原生滚动。自动轮播始终循环。
轮播停稳时,幻灯片用 CSS order 轮流出现在内容的两端,所以当前页的两侧始终都有幻灯片。它们在文档里保持原来的位置,所以屏幕阅读器和 Tab 都按幻灯片自身的顺序移动。内容需要像 flex 和 grid 那样,把幻灯片排成一行并保持均匀的间隔,还要在当前页两侧各放一页幻灯片。数量不够时,比如一次一屏只有两张幻灯片,最后一页的 Next 会改为滚回第一页。要移动一张卡片,比如让它在离开时滑走,请变换幻灯片内部的元素,而不是幻灯片本身,并给幻灯片设置 overflow: clip。浏览器测量幻灯片滚动了多远时,会把任何越过幻灯片的东西计算在内,循环就会在错误的位置绕回。
import {
Carousel,
CarouselContent,
CarouselItem,
CarouselNext,
CarouselPrevious,
CarouselViewport,
} from "@ui-sdk/solid/carousel"
import { For } from "solid-js"
const slides = [1, 2, 3, 4, 5]
function Example() {
return (
<Carousel aria-label="Featured" loop>
<div data-slot="row">
<CarouselPrevious aria-label="Previous slide">
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="m15 18-6-6 6-6" />
</svg>
</CarouselPrevious>
<CarouselViewport>
<CarouselContent>
<For each={slides}>
{(slide) => (
<CarouselItem>
<div data-slot="tile">{slide}</div>
</CarouselItem>
)}
</For>
</CarouselContent>
</CarouselViewport>
<CarouselNext aria-label="Next slide">
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="m9 18 6-6-6-6" />
</svg>
</CarouselNext>
</div>
</Carousel>
)
}
export { Example }对齐
align 让页面对齐到视口的 start(默认)、center 或 end。居中时,比视口窄的幻灯片会让相邻的幻灯片露出来。第一页和最后一页留在内容的两端,所以第一张幻灯片前面没有空白。
import {
Carousel,
CarouselContent,
CarouselItem,
CarouselNext,
CarouselPrevious,
CarouselViewport,
} from "@ui-sdk/solid/carousel"
import {
Select,
SelectContent,
SelectItem,
SelectItemIndicator,
SelectLabel,
SelectTrigger,
SelectValue,
} from "@ui-sdk/solid/select"
import { createSignal, For } from "solid-js"
type Align = "start" | "center" | "end"
const photos = [
{ name: "Dunes" },
{ name: "Forest" },
{ name: "Glacier" },
{ name: "Canyon" },
{ name: "Meadow" },
{ name: "Harbor" },
]
const alignments = [
{ value: "start", label: "Start" },
{ value: "center", label: "Center" },
{ value: "end", label: "End" },
]
function Example() {
const [align, setAlign] = createSignal<Align>("center")
return (
<div data-slot="stack">
<div data-slot="controls">
<Select
items={alignments}
value={align()}
onValueChange={(next) => next && setAlign(next as Align)}
>
<SelectLabel>Align</SelectLabel>
<SelectTrigger>
<SelectValue />
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="m6 9 6 6 6-6" />
</svg>
</SelectTrigger>
<SelectContent>
<For each={alignments}>
{(option) => (
<SelectItem value={option.value}>
{option.label}
<SelectItemIndicator>
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M20 6 9 17l-5-5" />
</svg>
</SelectItemIndicator>
</SelectItem>
)}
</For>
</SelectContent>
</Select>
</div>
<Carousel aria-label="Photos" align={align()} defaultPage={2}>
<div data-slot="row">
<CarouselPrevious aria-label="Previous slide">
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="m15 18-6-6 6-6" />
</svg>
</CarouselPrevious>
<CarouselViewport>
<CarouselContent>
<For each={photos}>
{(photo) => (
<CarouselItem>
<div data-slot="tile">{photo.name}</div>
</CarouselItem>
)}
</For>
</CarouselContent>
</CarouselViewport>
<CarouselNext aria-label="Next slide">
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="m9 18 6-6-6-6" />
</svg>
</CarouselNext>
</div>
</Carousel>
</div>
)
}
export { Example }默认页
defaultPage 是非受控时轮播起始的页。默认是 1。
import {
Carousel,
CarouselContent,
CarouselItem,
CarouselNext,
CarouselPrevious,
CarouselViewport,
} from "@ui-sdk/solid/carousel"
import { For } from "solid-js"
const slides = [1, 2, 3, 4, 5]
function Example() {
return (
<Carousel aria-label="Featured" defaultPage={3}>
<div data-slot="row">
<CarouselPrevious aria-label="Previous slide">
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="m15 18-6-6 6-6" />
</svg>
</CarouselPrevious>
<CarouselViewport>
<CarouselContent>
<For each={slides}>
{(slide) => (
<CarouselItem>
<div data-slot="tile">{slide}</div>
</CarouselItem>
)}
</For>
</CarouselContent>
</CarouselViewport>
<CarouselNext aria-label="Next slide">
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="m9 18 6-6-6-6" />
</svg>
</CarouselNext>
</div>
</Carousel>
)
}
export { Example }指示器
指示器是一个选项卡列表:当前页只有一个 Tab 停靠点,方向键在它们之间移动并显示对应的页,Home 和 End 跳到两端。每个指示器控制它那一页的幻灯片。
每张幻灯片写一个。超出页数的指示器会隐藏自己,所以同一份标记在任意数量的幻灯片下都能用。指示器的 page 从它们的顺序推断;传入它,才能在服务端渲染出选中的那个。
import {
Carousel,
CarouselContent,
CarouselIndicator,
CarouselIndicatorGroup,
CarouselItem,
CarouselViewport,
} from "@ui-sdk/solid/carousel"
import { For } from "solid-js"
const photos = [
{ name: "Dunes" },
{ name: "Forest" },
{ name: "Glacier" },
{ name: "Canyon" },
{ name: "Meadow" },
{ name: "Harbor" },
]
function Example() {
return (
<Carousel aria-label="Photos">
<CarouselViewport>
<CarouselContent>
<For each={photos}>
{(photo) => (
<CarouselItem>
<div data-slot="tile">{photo.name}</div>
</CarouselItem>
)}
</For>
</CarouselContent>
</CarouselViewport>
<CarouselIndicatorGroup aria-label="Choose a photo">
<For each={photos}>
{(photo, index) => (
<CarouselIndicator page={index() + 1} aria-label={photo.name} />
)}
</For>
</CarouselIndicatorGroup>
</Carousel>
)
}
export { Example }页
slidesPerPage 是一页放多少张幻灯片:Next 每次移动这么多,每个指示器也代表这么多。"auto" 按能显示的数量来放。无法从起始位置排满的页,比如最后几张幻灯片,会并入最后一页。在显示三张幻灯片的情况下,五张幻灯片按每页一张算有三页,按每页三张算有两页。
import {
Carousel,
CarouselContent,
CarouselIndicator,
CarouselIndicatorGroup,
CarouselItem,
CarouselNext,
CarouselPrevious,
CarouselViewport,
} from "@ui-sdk/solid/carousel"
import { For } from "solid-js"
const products = [1, 2, 3, 4, 5, 6, 7, 8]
function Example() {
return (
<Carousel aria-label="Products" slidesPerPage={3}>
<div data-slot="row">
<CarouselPrevious aria-label="Previous page">
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="m15 18-6-6 6-6" />
</svg>
</CarouselPrevious>
<CarouselViewport>
<CarouselContent>
<For each={products}>
{(product) => (
<CarouselItem>
<div data-slot="tile">{product}</div>
</CarouselItem>
)}
</For>
</CarouselContent>
</CarouselViewport>
<CarouselNext aria-label="Next page">
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="m9 18 6-6-6-6" />
</svg>
</CarouselNext>
</div>
<div data-slot="row">
<CarouselIndicatorGroup aria-label="Choose a page">
{(state) =>
Array.from({ length: state.pageCount ?? 3 }, (_, index) => (
<CarouselIndicator
page={index + 1}
aria-label={`Page ${index + 1}`}
/>
))
}
</CarouselIndicatorGroup>
</div>
</Carousel>
)
}
export { Example }缩略图
图库和一条缩略图带共享选中的页。缩略图轮播用 dragFree 自由滚动,按能显示的数量来放。按压缩略图会选中它的幻灯片。
import {
Carousel,
CarouselContent,
CarouselItem,
CarouselViewport,
} from "@ui-sdk/solid/carousel"
import { createSignal, For } from "solid-js"
const photos = [
{ name: "Dunes" },
{ name: "Forest" },
{ name: "Glacier" },
{ name: "Canyon" },
{ name: "Meadow" },
{ name: "Harbor" },
]
function Example() {
const [page, setPage] = createSignal(1)
let strip: HTMLDivElement | undefined
const show = (next: number) => {
setPage(next)
strip
?.querySelectorAll("button")
[next - 1]?.scrollIntoView({ block: "nearest", inline: "nearest" })
}
return (
<div data-slot="stack">
<Carousel aria-label="Photos" page={page()} onPageChange={show}>
<CarouselViewport>
<CarouselContent>
<For each={photos}>
{(photo) => (
<CarouselItem>
<div data-slot="tile">{photo.name}</div>
</CarouselItem>
)}
</For>
</CarouselContent>
</CarouselViewport>
</Carousel>
<Carousel
ref={strip}
aria-label="Thumbnails"
dragFree
slidesPerPage="auto"
>
<CarouselViewport>
<CarouselContent>
<For each={photos}>
{(photo, index) => (
<CarouselItem aria-label={photo.name}>
<button
type="button"
aria-pressed={page() === index() + 1 ? "true" : "false"}
onClick={() => setPage(index() + 1)}
>
{photo.name}
</button>
</CarouselItem>
)}
</For>
</CarouselContent>
</CarouselViewport>
</Carousel>
</div>
)
}
export { Example }自动轮播
defaultPlaying 让轮播开始自动播放,每隔 interval 毫秒换一页(默认 5000)。CarouselPlayToggle 启动和停止它;用它的状态里的 playing 给它设置名称。
按照轮播模式的要求,键盘焦点移入时轮播停止,在用户要求之前不会重新开始,鼠标悬停时也会暂停。标签页隐藏、轮播滚出视野以及手指按住期间,它同样会暂停。自己切换幻灯片会停止轮播。只有不在轮播时,幻灯片才是礼貌的实时区域(polite live region),所以屏幕阅读器不会每隔几秒被打断。用户偏好减少动态效果时,它不会自行开始。
根上的 --carousel-interval 是间隔,暂停期间带有 data-paused,所以进度条可以用 CSS 自己计时。
import {
Carousel,
CarouselContent,
CarouselItem,
CarouselNext,
CarouselPlayToggle,
CarouselPrevious,
CarouselViewport,
} from "@ui-sdk/solid/carousel"
import { For } from "solid-js"
import { useLog } from "./log"
const photos = [
{ name: "Dunes" },
{ name: "Forest" },
{ name: "Glacier" },
{ name: "Canyon" },
{ name: "Meadow" },
{ name: "Harbor" },
]
function Example() {
const log = useLog()
return (
<Carousel
aria-label="Photos"
defaultPlaying
interval={4000}
onPlayingChange={(playing, details) =>
log(`${playing ? "Playing" : "Stopped"} (${details.reason})`)
}
>
<div data-slot="controls">
<CarouselPlayToggle>
{(state) => (state.playing ? "Pause" : "Play")}
</CarouselPlayToggle>
</div>
<div data-slot="row">
<CarouselPrevious aria-label="Previous slide">
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="m15 18-6-6 6-6" />
</svg>
</CarouselPrevious>
<CarouselViewport>
<CarouselContent>
<For each={photos}>
{(photo) => (
<CarouselItem>
<div data-slot="tile">{photo.name}</div>
</CarouselItem>
)}
</For>
</CarouselContent>
</CarouselViewport>
<CarouselNext aria-label="Next slide">
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="m9 18 6-6-6-6" />
</svg>
</CarouselNext>
</div>
</Carousel>
)
}
export { Example }进度
根上的 --carousel-progress 表示幻灯片滚动了多远,从第一页的 0 到最后一页的 1,在滚动或弹簧动画的每一帧更新,不会引起重新渲染,所以进度条可以用 CSS 跟随它。启用 loop 时,它从 0 走到 1 再回到 0。控制器的 getProgress() 读取同一个数字。
每张幻灯片都有自己的 --carousel-item-progress,它的页停稳时是 0。幻灯片位于前方一页时,它向 1 上升;位于后方一页时,它向 -1 下降,所以幻灯片可以在进出时用 CSS 淡入淡出、缩放或倾斜。用 var(--carousel-item-progress, 0) 读取它,这样首次绘制时也有值。
onPageChangeComplete 在幻灯片停稳到某一页后运行,无论是弹簧动画、拖动还是滚动之后。把会让动画卡顿的工作放在这里,比如加载后面幻灯片的图片。
import {
Carousel,
CarouselContent,
CarouselItem,
CarouselNext,
CarouselPrevious,
CarouselViewport,
} from "@ui-sdk/solid/carousel"
import { For } from "solid-js"
import { useLog } from "./log"
const slides = [1, 2, 3, 4, 5]
function Example() {
const log = useLog()
return (
<Carousel
aria-label="Featured"
onPageChangeComplete={(page) => log(`Rested on slide ${page}`)}
>
<div data-slot="row">
<CarouselPrevious aria-label="Previous slide">
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="m15 18-6-6 6-6" />
</svg>
</CarouselPrevious>
<CarouselViewport>
<CarouselContent>
<For each={slides}>
{(slide) => (
<CarouselItem>
<div data-slot="tile">{slide}</div>
</CarouselItem>
)}
</For>
</CarouselContent>
</CarouselViewport>
<CarouselNext aria-label="Next slide">
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="m9 18 6-6-6-6" />
</svg>
</CarouselNext>
</div>
<div data-slot="row">
<div data-slot="bar">
<div />
</div>
</div>
</Carousel>
)
}
export { Example }受控
传入 page 和 onPageChange 来控制页,从 1 开始。根的状态里有 pageCount,在幻灯片测量完成之前为 null。
每次变更都带一个原因:next-press 和 previous-press 来自这些部件,item-press 来自指示器或露出的幻灯片,list-navigation 来自方向键,swipe 来自手指或鼠标拖动,scroll 来自滚轮或触控板,timeout 来自轮播,imperative 来自控制器。调用 details.cancel() 留在当前页:滑动或拖动会弹回。受控的页没有变化时,也会滚回原处。
import {
Carousel,
CarouselContent,
CarouselItem,
CarouselNext,
CarouselPrevious,
CarouselViewport,
} from "@ui-sdk/solid/carousel"
import { createSignal, For } from "solid-js"
import { useLog } from "./log"
const slides = [1, 2, 3, 4, 5]
function Example() {
const [page, setPage] = createSignal(1)
const log = useLog()
return (
<Carousel
aria-label="Featured"
page={page()}
onPageChange={(next, details) => {
setPage(next)
log(`Page ${next} (${details.reason})`)
}}
>
<div data-slot="row">
<CarouselPrevious aria-label="Previous slide">
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="m15 18-6-6 6-6" />
</svg>
</CarouselPrevious>
<CarouselViewport>
<CarouselContent>
<For each={slides}>
{(slide) => (
<CarouselItem>
<div data-slot="tile">{slide}</div>
</CarouselItem>
)}
</For>
</CarouselContent>
</CarouselViewport>
<CarouselNext aria-label="Next slide">
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="m9 18 6-6-6-6" />
</svg>
</CarouselNext>
</div>
</Carousel>
)
}
export { Example }从任何地方翻页
来自 createCarouselController() 的控制器可以从任何地方给轮播翻页。把它作为 controller 传给轮播,以及放在它外面的 CarouselPrevious、CarouselNext、CarouselIndicatorGroup 或 CarouselPlayToggle,比如放在区块标题里。
drag={false} 关闭滑动和拖动,所以只有部件、按键和控制器能移动它。
import {
Carousel,
CarouselContent,
CarouselItem,
CarouselNext,
CarouselPrevious,
CarouselViewport,
createCarouselController,
} from "@ui-sdk/solid/carousel"
import { For } from "solid-js"
const slides = [1, 2, 3, 4, 5]
function Example() {
const carousel = createCarouselController()
return (
<div data-slot="stack">
<div data-slot="controls">
<CarouselPrevious controller={carousel} aria-label="Previous slide">
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="m15 18-6-6 6-6" />
</svg>
</CarouselPrevious>
<CarouselNext controller={carousel} aria-label="Next slide">
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="m9 18 6-6-6-6" />
</svg>
</CarouselNext>
<button type="button" onClick={() => carousel.setPage(5)}>
Show the Last Slide
</button>
</div>
<Carousel aria-label="Featured" controller={carousel} drag={false}>
<CarouselViewport>
<CarouselContent>
<For each={slides}>
{(slide) => (
<CarouselItem>
<div data-slot="tile">{slide}</div>
</CarouselItem>
)}
</For>
</CarouselContent>
</CarouselViewport>
</Carousel>
</div>
)
}
export { Example }滑动与拖动
触摸、触控板和滚轮以原生方式滚动视口,翻页由 CSS 滚动吸附完成。原生滚动和吸附在 JavaScript 加载之前也能工作。鼠标或触控笔也可以拖动幻灯片:它们跟随指针,越过两端时被拉伸,然后按松开时的速度弹到一次快速甩动会到达的页。真正移动过的拖动不会点击它起始位置上的链接,幻灯片里的字段仍然接收指针事件。按压边缘露出的幻灯片会翻到它那一页。
没有设置 skipSnaps 时,一次滑动最多移动一页。dragFree 让滑动一路滑到停下为止,最近的页成为当前页。
按钮、按键、指示器、轮播和控制器会让滚动位置产生动画。在移动过程中再次按压会更新目标位置。减少动态效果会让这些变更立即生效。
关闭轮播
disabled 暂时关掉轮播,比如在宽屏上,同样的幻灯片会排成网格。各部件会去掉自己的角色、幻灯片名称和内联样式,每张幻灯片仍然可以到达,视口不再响应按键和滑动翻页,Previous、Next、指示器和播放切换按钮都会隐藏。重新打开后,它会再次测量幻灯片并显示当前页。
const isWide = createMediaQuery("(min-width: 768px)")
return (
<Carousel aria-label="Featured products" disabled={isWide()}>
{/* Viewport, slides and controls. */}
</Carousel>
)自定义渲染
每个部件都接受 render,一个接收要展开的 props 和部件状态的函数。class、style 和 children 可以是同一份状态的函数:幻灯片的 index、active 和 inView,翻页按钮的 disabled,指示器的 page 和 selected,播放切换按钮的 playing 和 paused。
import {
Carousel,
CarouselContent,
CarouselItem,
CarouselNext,
CarouselPrevious,
CarouselViewport,
} from "@ui-sdk/solid/carousel"
import { For } from "solid-js"
const photos = [
{ name: "Dunes" },
{ name: "Forest" },
{ name: "Glacier" },
{ name: "Canyon" },
{ name: "Meadow" },
{ name: "Harbor" },
]
const nextFocused = () =>
typeof document !== "undefined" &&
document.activeElement?.getAttribute("data-slot") === "carousel-next"
function Example() {
return (
<Carousel aria-label="Photos">
<CarouselViewport>
<CarouselContent>
<For each={photos}>
{(photo) => (
<CarouselItem>
{(state) => (
<div data-slot="tile">
{photo.name}
<span data-slot="hint">
{state.index + 1} / {photos.length}
{state.active && " · showing"}
</span>
</div>
)}
</CarouselItem>
)}
</For>
</CarouselContent>
</CarouselViewport>
<div data-slot="row">
<CarouselPrevious>
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="m15 18-6-6 6-6" />
</svg>
Previous
</CarouselPrevious>
<CarouselNext
render={(props, state) =>
state.disabled ? (
<a
href="https://example.com/gallery"
ref={(link) =>
nextFocused() && queueMicrotask(() => link.focus())
}
>
See all photos
</a>
) : (
<button {...props}>
Next
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="m9 18 6-6-6-6" />
</svg>
</button>
)
}
/>
</div>
</Carousel>
)
}
export { Example }样式
在到达两端时给 Previous 和 Next 用 data-disabled,给当前指示器用 data-selected,给当前页的幻灯片用 data-active,给视野中的幻灯片用 data-in-view,并给根用 data-playing 和 data-paused。
幻灯片自己决定尺寸:一次显示一张时给它 100% 的 flex-basis,显示三张时给三分之一,并把间隔放在内容上,从每个 basis 里扣除。视口会以内联样式写入滚动所需的少数几项:它的 overflow、scroll-snap-type 和 overscroll-behavior。幻灯片会得到 flex-shrink: 0 和它的吸附对齐。内容是 flex 行,垂直时是列。要改为把幻灯片排成网格,在它上面设置 --carousel-display: grid。如果愿意,可以用 scrollbar-width: none 隐藏滚动条。
每个部件都有一个 data-slot,比如 carousel-item,它的状态属性列在数据属性下。
Carousel
| 变量 | 内容 |
|---|---|
--carousel-interval | How long each page shows while rotating, like 500ms. Time a progress bar's animation with it. |
--carousel-progress | How far the slides have scrolled, from 0 at the first page to 1 at the last, or round the loop. It follows every frame of a scroll or spring. |
CarouselContent
| 变量 | 内容 |
|---|---|
--carousel-display | Set it yourself: how the content lays out its slides, like grid. Flex by default. |
CarouselItem
| 变量 | 内容 |
|---|---|
--carousel-item-progress | How far the slide is from its page's resting place, from -1 a page behind to 1 a page ahead, and 0 at rest. It follows every frame of a scroll or spring. |
数据属性
Carousel
[data-slot="carousel"]
| 属性 | 含义 |
|---|---|
data-orientation | horizontalverticalWhich way the slides scroll, and which arrow keys page. |
data-playing | Present while it rotates on its own. |
data-paused | Present while rotation is paused for now: hovered, the tab hidden, scrolled out of view or held. Pause a progress animation with it. |
CarouselViewport
[data-slot="carousel-viewport"]
| 属性 | 含义 |
|---|---|
data-orientation | horizontalverticalWhich way the slides scroll, and which arrow keys page. |
data-dragging | Present while a mouse or pen drags the slides. |
CarouselContent
[data-slot="carousel-content"]
| 属性 | 含义 |
|---|---|
data-orientation | horizontalverticalWhich way the slides scroll, and which arrow keys page. |
CarouselItem
[data-slot="carousel-item"]
| 属性 | 含义 |
|---|---|
data-orientation | horizontalverticalWhich way the slides scroll, and which arrow keys page. |
data-active | Present on the slides of the current page. |
data-in-view | Present on slides at least half in view. Slides without it are inert and hidden from screen readers. |
CarouselPrevious
[data-slot="carousel-previous"]
| 属性 | 含义 |
|---|---|
data-disabled | Present on Previous or Next when there's no page that way, beside aria-disabled. It stays focusable and does nothing. |
CarouselIndicator
[data-slot="carousel-indicator"]
| 属性 | 含义 |
|---|---|
data-selected | Present on the current page's indicator, beside aria-selected. |
CarouselPlayToggle
[data-slot="carousel-play-toggle"]
| 属性 | 含义 |
|---|---|
data-playing | Present while it rotates on its own. |
data-paused | Present while rotation is paused for now: hovered, the tab hidden, scrolled out of view or held. Pause a progress animation with it. |
API 参考
属性与回调与下面相同,都作为 Solid props。
Carousel
page?number- The current page, from 1. Pass it to control the carousel.
defaultPage?number- The page it starts on, from 1, when uncontrolled.
onPageChange?((page: number, details: ChangeDetails<CarouselPageChangeReason>) => void)- Runs when the page wants to change.
details.reasonsays why, anddetails.cancel()stays on the page. onPageChangeComplete?((page: number) => void)- Runs once the slides come to rest on a page, after a spring, a drag or a scroll, with that page. Start work there that would stutter the motion.
playing?boolean- Whether it rotates through the pages on its own. Pass it to control rotation.
defaultPlaying?boolean- Whether it starts rotating, when uncontrolled. It doesn't when the user prefers reduced motion; the play toggle still starts it.
onPlayingChange?((playing: boolean, details: ChangeDetails<CarouselPlayingChangeReason>) => void)- Runs when rotation wants to start or stop. Keyboard focus moving in and the user paging stop it, as the carousel pattern asks.
interval?number- How long each page shows while rotating, in ms. Hovering, a hidden tab and scrolling the carousel out of view pause it.
orientation?CarouselOrientation- Which way the slides scroll, and which arrow keys page.
align?CarouselAlign- Where a page lines up in the viewport.
slidesPerPage?CarouselSlidesPerPage- How many slides one page holds: Next moves this many, and each indicator stands for this many.
"auto"fits as many as the viewport shows. loop?boolean- Whether the slides go round: Next on the last page goes to the first, which comes in after the last, and a swipe back from the first page reaches the last. With fewer than a page of slides to either side, Next on the last page scrolls back to the first instead.
skipSnaps?boolean- Whether a fast swipe can pass over pages. Without it, one swipe moves one page.
dragFree?boolean- Whether swipes and drags coast to wherever they stop instead of a page. The nearest page becomes the current one.
drag?boolean- Whether swiping, dragging and scrolling move the slides. Without it, only the parts, keys and controllers do.
disabled?boolean- Whether it stops being a carousel for now, like at a breakpoint where the slides lay out as a grid. The parts drop their roles, inline styles and listeners, and the controls hide.
controller?object- Pages the carousel from anywhere. Create one with
createCarouselController(). debug?boolean- Logs every state change with its reason to the console, in development builds.
CarouselViewport
滚动的区域。渲染一个原生滚动和吸附的 div,并为方向键接收焦点。
CarouselContent
容纳幻灯片。渲染一个 div,播报进入视野的幻灯片,轮播时除外。
CarouselItem
一张幻灯片。渲染一个带 group 角色的 div,按位置命名,比如“2 of 5”。
CarouselPrevious
controller?object- The carousel this part drives when it isn't inside one, like buttons in a page header.
CarouselNext
显示下一页。接受与 CarouselPrevious 相同的 props。
CarouselIndicatorGroup
把指示器分组。渲染一个带 tablist 角色的 div。接受与 CarouselPrevious 相同的 props。
CarouselIndicator
page?number- The page it shows and selects, from 1. Inferred from the indicators' order when left out.
CarouselPlayToggle
启动和停止轮播。渲染一个 button。接受与 CarouselPrevious 相同的 props。
状态
每个部件的渲染函数、基于状态的类名和槽位会收到什么。
Carousel:
pagenumber- The current page, from 1.
pageCountnumber | null- How many pages there are, or null before the slides are measured, like on the server.
playingboolean- Whether it rotates on its own.
orientationCarouselOrientation- Which way the slides scroll.
CarouselViewport:
orientationCarouselOrientation- Which way the slides scroll.
draggingboolean- Whether a mouse or pen is dragging the slides.
CarouselContent:
orientationCarouselOrientation- Which way the slides scroll.
CarouselItem:
indexnumber- The slide's position among the slides, from 0. -1 until it's measured.
activeboolean- Whether the slide belongs to the current page.
inViewboolean- Whether at least half of the slide shows. Slides out of view are inert.
CarouselPrevious and CarouselNext:
disabledboolean- Whether there's no page that way, so pressing does nothing. It stays focusable.
CarouselIndicatorGroup:
pagenumber- The current page, from 1.
pageCountnumber | null- How many pages there are, or null before the slides are measured.
CarouselIndicator:
pagenumber- The page it stands for, from 1, or 0 before it's known.
selectedboolean- Whether its page is the current one.
CarouselPlayToggle:
playingboolean- Whether it rotates on its own.
pausedboolean- Whether rotation is paused for now: hovered, the tab hidden, scrolled out of view or held.
原因
details.reason 说明页为什么变化。
previous-pressMouseEvent | KeyboardEvent- A pagination's or a carousel's Previous part was pressed.
next-pressMouseEvent | KeyboardEvent- A pagination's or a carousel's Next part was pressed.
item-pressMouseEvent | KeyboardEvent- A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
list-navigationKeyboardEvent- Arrow, Home or End keys moved the selection, typing picked an item, or Ctrl or ⌘ with A selected every item of a listbox.
swipeTouchEvent | PointerEvent- A swipe gesture: a finger, mouse or pen dragged it.
scrollEvent | undefined- The user scrolled a carousel some other way: a wheel, a trackpad, a scrollbar, or the browser bringing focus or a find in page into view.
timeoutnone- A duration ran out, like a toast's, or a rotating carousel's interval.
content-resizenone- The content or the screen changed size, and the drawer's snap point or the carousel's page went away, so it moved to the nearest one.
imperativenone- A controller or
apicall.
以及轮播为什么开始或停止。
previous-pressMouseEvent | KeyboardEvent- A pagination's or a carousel's Previous part was pressed.
next-pressMouseEvent | KeyboardEvent- A pagination's or a carousel's Next part was pressed.
item-pressMouseEvent | KeyboardEvent- A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
list-navigationKeyboardEvent- Arrow, Home or End keys moved the selection, typing picked an item, or Ctrl or ⌘ with A selected every item of a listbox.
swipeTouchEvent | PointerEvent- A swipe gesture: a finger, mouse or pen dragged it.
scrollEvent | undefined- The user scrolled a carousel some other way: a wheel, a trackpad, a scrollbar, or the browser bringing focus or a find in page into view.
imperativenone- A controller or
apicall. toggle-pressMouseEvent | KeyboardEvent- A toggle was pressed: a password input's, which shows or hides the password, or a carousel's, which starts or stops rotation.
focus-inFocusEvent- Keyboard focus moved into the component, which stops a rotating carousel, as the carousel pattern asks, or onto a canvas item, which brought it into view, or onto a calendar's day another way, like a screen reader's.
控制器
用 createCarouselController() 创建一个,并作为 controller 传入。
每个写入方法都接受一个可选的 { reason, event },传给变更回调,并在变更被取消或无处可去时返回 false。
getPage()() => number- The current page, from 1.
getPageCount()() => number | null- How many pages there are, or null before the carousel has measured its slides.
setPage(page, options?)(page: number, options?: CarouselPageOptions | undefined) => boolean- Goes to a page, from 1, clamped to the pages there are. Returns false when canceled or already there.
next(options?)(options?: CarouselPageOptions | undefined) => boolean- Goes to the next page, or the first one after the last with
loop. Returns false at the end. previous(options?)(options?: CarouselPageOptions | undefined) => boolean- Goes to the previous page, or the last one before the first with
loop. Returns false at the start. canNext()() => boolean- Whether there's a next page, always with
loop. canPrevious()() => boolean- Whether there's a previous page, always with
loop. getProgress()() => number- How far the slides have scrolled, from 0 at the first page to 1 at the last, or round the loop. Also
--carousel-progresson the root. isPlaying()() => boolean- Whether it rotates on its own.
setPlaying(playing, options?)(playing: boolean, options?: CarouselPlayingOptions | undefined) => boolean- Starts or stops rotation. Returns false when canceled or unchanged.
play(options?)(options?: CarouselPlayingOptions | undefined) => boolean- Starts rotation.
pause(options?)(options?: CarouselPlayingOptions | undefined) => boolean- Stops rotation.
事件
回调先收到新值,然后收到详情。
| 属性 | 所属 | 收到 |
|---|---|---|
onPageChange | Carousel | (page, details):新页,以及原因 |
onPageChangeComplete | Carousel | (page):幻灯片停稳时所在的页 |
onPlayingChange | Carousel | (playing, details):是否在轮播,以及原因 |
无障碍
它遵循 WAI-ARIA 轮播模式:一个描述为轮播的区域,幻灯片是 group,被描述为幻灯片并按位置命名,Previous 和 Next 控制幻灯片,一个轮播控件,指示器是选项卡列表。下面每一行都是一个自动化测试。
每张幻灯片按位置命名,比如“1 of 5”,除非它有自己的 aria-label,你也可以用它来翻译名称。露出不到一半的幻灯片是 inert,并对屏幕阅读器隐藏,所以 Tab 和虚拟光标只能到达可见的内容。
键盘
方向键跟随方向设置,在从右到左(RTL)的文本中会交换左右。
| 按键 | 作用 |
|---|---|
| Tab | 到达播放切换按钮、视野中幻灯片里的链接和控件、Previous、Next 和当前指示器 |
| ArrowRight, ArrowLeft | 在视口里,下一页和上一页。垂直时是 ArrowDown 和 ArrowUp |
| Home, End | 在视口或指示器里,第一页和最后一页 |
| ArrowRight, ArrowLeft, ArrowDown, ArrowUp | 在指示器里,下一个和上一个指示器,并显示它对应的页 |
| Enter, Space | 按压 Previous、Next、指示器或播放切换按钮 |
幻灯片里的字段和控件保留自己的方向键:文本字段的光标会移动,轮播保持不动。当方向键从有焦点的幻灯片翻走时,焦点会移到进入视野的那张幻灯片,所以它永远不会留在看不见的东西上。Previous 和 Next 在两端仍然可以聚焦,并带上 aria-disabled,所以 Next 到达最后一张幻灯片时,焦点不会掉到页面上。
经过测试的行为
- The carousel is a named region described as a carousel.
- Each slide is a group described as a slide.
- The first slide shows first.
- The content lays its slides out as --carousel-display says.
- Next shows the next slide.
- Previous shows the previous slide.
- Previous is disabled on the first slide and Next on the last.
- Next on the last slide does nothing.
- Next and Previous are buttons that don't submit a form.
- ArrowRight in a slide shows the next slide, and ArrowLeft the previous.
- ArrowLeft on the first slide stays there.
- With three slides to a view, Next moves one slide, and the last page shows the last three.
- Three slides to a page move three at a time.
- Auto pages fit as many slides as show.
- It can start on another page.
- A controller pages it from outside.
- It reports the page once the slides come to rest.
- Next on the last slide shows the first.
- Previous on the first slide shows the last.
- Previous and Next are never disabled.
- Next on the last slide carries on the same way to the first.
- Pressing Next quickly keeps going forward, round past the last slide.
- A loop with too few slides to go round says so in development.
- Next pressed faster than the slides land never scrolls back.
- A mouse drag back from the first slide shows the last.
- With three slides to a view, the last slide shows before the first.
- A vertical carousel drags down from the first slide to the last.
- Dragging the slides with a mouse shows the next one.
- A short, slow drag settles back on the same slide.
- Dragging back shows the previous slide.
- A drag that starts on a link doesn't follow it.
- Without dragging, a drag moves nothing.
- A vertical carousel drags up and down.
- Pressing keys with no waits lands on the right slide.
- A fast flick moves one page, not more.
- The current slide stays in view when the slides change size.
运行于 React、Vue 和 web components。
模式之外:
- Next keeps focus when it reaches the last slide.
- Tab reaches only the slides in view.
- Slides out of view are hidden from assistive technology.
- Arrow keys bring the next slide in and move focus to it.
- A text field in a slide keeps its arrow keys.
- Home and End go to the first and last slide.
- A vertical carousel pages with ArrowDown and ArrowUp.
- Indicators are a tablist with the current page selected.
- Pressing an indicator shows its page.
- Arrow keys move between indicators and show their page.
- The indicators are one tab stop, on the current page.
- An indicator controls the slides of its page.
- Indicators past the page count hide themselves.
- A change can be canceled.
- A canceled drag springs back.
- Every change says why.
- A horizontal wheel scrolls to the next slide.
- With loop, a wheel back from the first slide scrolls natively to the last.
- --carousel-progress on the root follows the slides, for progress bars in CSS.
- With loop, --carousel-progress goes round, whatever the track's rotation.
- Disabled, it's no carousel until it's turned back on, like at a breakpoint.
- Turned off while a finger is down, it rotates again once it's back on.
- --carousel-item-progress on each slide says how far it is from rest.
- With loop, --carousel-item-progress follows the slides round.
- A press on a slide peeking in at the edge pages to it.
- A press on a control laid over a peeking slide doesn't page.
- With loop, a press on the slide peeking in before the first pages back round to it.
- Next outside the carousel works through its controller.
- It rotates on its own, past the last slide to the first.
- The play toggle stops and starts rotation, and its name says which.
- Keyboard focus moving in stops rotation, as the pattern asks.
- Hovering pauses rotation, and leaving resumes it.
- Pressing Next stops rotation.
- The slides are a live region only while not rotating.
- It doesn't start rotating when the user prefers reduced motion.
- Reduced motion pages without animating.
- Indicators follow a change in size.
运行于 React、Vue 和 web components。
在每个经过测试的框架里,屏幕阅读器听到的内容相同,由虚拟屏幕阅读器记录:
- Announcements while using the carousel with a keyboard.
运行于 React、Vue 和 web components。