Carousel
用原生滚动、键盘操作和可选的自动轮播逐页浏览幻灯片。
用 Carousel 一次显示一屏幻灯片,比如产品照片或精选故事。它使用原生滚动,所以滑动和触控板都能用,Previous 和 Next 按钮用来翻页。
import "@ui-sdk/web/carousel"
import { ChevronLeft, ChevronRight, createElement } from "lucide"
const slides = [1, 2, 3, 4, 5]
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-carousel aria-label="Featured">
<div data-slot="row">
<ui-carousel-previous>
<button aria-label="Previous slide">${createElement(ChevronLeft, { "aria-hidden": "true" }).outerHTML}</button>
</ui-carousel-previous>
<ui-carousel-viewport>
<ui-carousel-content>
${slides.map((slide) => `<ui-carousel-item><div data-slot="tile">${slide}</div></ui-carousel-item>`).join("")}
</ui-carousel-content>
</ui-carousel-viewport>
<ui-carousel-next>
<button aria-label="Next slide">${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}</button>
</ui-carousel-next>
</div>
</ui-carousel>
`
}
export { mount }安装
npm install @ui-sdk/web @ui-sdk/core导入组件会定义它的元素。在服务端,这次导入不会做任何事。
import "@ui-sdk/web/carousel"组合
用下面的组合构建 ui-carousel:
ui-carousel
├── ui-carousel-viewport
│ └── ui-carousel-content
│ ├── ui-carousel-item
│ └── ui-carousel-item
├── ui-carousel-previous
│ └── button
└── ui-carousel-next
└── button把幻灯片放进视口,然后加上你需要的控件。
视口是滚动的窗口,内容则是里面那一排幻灯片,一个 flex 行(垂直时是列)。用 aria-label 给轮播命名,比如“Featured products”。Previous、Next、指示器和播放切换按钮会包住你自己的 <button>:给它文字,或者当它只放图标时给它 aria-label。
用法
导入部件并把它们组合起来:
<script type="module">
import "@ui-sdk/web/carousel"
</script>
<ui-carousel aria-label="Featured">
<ui-carousel-viewport>
<ui-carousel-content>
<ui-carousel-item>First slide</ui-carousel-item>
<ui-carousel-item>Second slide</ui-carousel-item>
</ui-carousel-content>
</ui-carousel-viewport>
<ui-carousel-previous><button>Previous</button></ui-carousel-previous>
<ui-carousel-next><button>Next</button></ui-carousel-next>
</ui-carousel>垂直
orientation="vertical" 让幻灯片上下滚动。给视口一个高度。上下方向键用来翻页,而不是左右方向键。
import "@ui-sdk/web/carousel"
import { ChevronDown, ChevronUp, createElement } from "lucide"
const slides = [1, 2, 3, 4, 5]
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-carousel aria-label="Featured" orientation="vertical">
<ui-carousel-viewport>
<ui-carousel-content>
${slides.map((slide) => `<ui-carousel-item><div data-slot="tile">${slide}</div></ui-carousel-item>`).join("")}
</ui-carousel-content>
</ui-carousel-viewport>
<div data-slot="row">
<ui-carousel-previous>
<button aria-label="Previous slide">${createElement(ChevronUp, { "aria-hidden": "true" }).outerHTML}</button>
</ui-carousel-previous>
<ui-carousel-next>
<button aria-label="Next slide">${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}</button>
</ui-carousel-next>
</div>
</ui-carousel>
`
}
export { mount }循环
loop 让幻灯片首尾相接。在最后一页按 Next 会到第一页,而第一页排在最后一张之后;从第一页往回滑动、拖动或滚轮滚动,会到达最后一页,全程都是原生滚动。自动轮播始终循环。
轮播停稳时,幻灯片用 CSS order 轮流出现在内容的两端,所以当前页的两侧始终都有幻灯片。它们在文档里保持原来的位置,所以屏幕阅读器和 Tab 都按幻灯片自身的顺序移动。内容需要像 flex 和 grid 那样,把幻灯片排成一行并保持均匀的间隔,还要在当前页两侧各放一页幻灯片。数量不够时,比如一次一屏只有两张幻灯片,最后一页的 Next 会改为滚回第一页。要移动一张卡片,比如让它在离开时滑走,请变换幻灯片内部的元素,而不是幻灯片本身,并给幻灯片设置 overflow: clip。浏览器测量幻灯片滚动了多远时,会把任何越过幻灯片的东西计算在内,循环就会在错误的位置绕回。
import "@ui-sdk/web/carousel"
import { ChevronLeft, ChevronRight, createElement } from "lucide"
const slides = [1, 2, 3, 4, 5]
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-carousel aria-label="Featured" loop>
<div data-slot="row">
<ui-carousel-previous>
<button aria-label="Previous slide">${createElement(ChevronLeft, { "aria-hidden": "true" }).outerHTML}</button>
</ui-carousel-previous>
<ui-carousel-viewport>
<ui-carousel-content>
${slides.map((slide) => `<ui-carousel-item><div data-slot="tile">${slide}</div></ui-carousel-item>`).join("")}
</ui-carousel-content>
</ui-carousel-viewport>
<ui-carousel-next>
<button aria-label="Next slide">${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}</button>
</ui-carousel-next>
</div>
</ui-carousel>
`
}
export { mount }对齐
align 让页面对齐到视口的 start(默认)、center 或 end。居中时,比视口窄的幻灯片会让相邻的幻灯片露出来。第一页和最后一页留在内容的两端,所以第一张幻灯片前面没有空白。
import "@ui-sdk/web/carousel"
import "@ui-sdk/web/select"
import {
Check,
ChevronDown,
ChevronLeft,
ChevronRight,
createElement,
} from "lucide"
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 mount(root: HTMLElement) {
root.innerHTML = `
<div data-slot="stack">
<div data-slot="controls">
<ui-select default-value="center">
<ui-select-label>Align</ui-select-label>
<ui-select-trigger>
<button>
<ui-select-value></ui-select-value>
${createElement(ChevronDown, { "aria-hidden": "true" }).outerHTML}
</button>
</ui-select-trigger>
<ui-select-content hidden>
${alignments
.map(
(option) => `
<ui-select-item value="${option.value}">
${option.label}
<ui-select-item-indicator>${createElement(Check, { "aria-hidden": "true" }).outerHTML}</ui-select-item-indicator>
</ui-select-item>
`
)
.join("")}
</ui-select-content>
</ui-select>
</div>
<ui-carousel aria-label="Photos" align="center" default-page="2">
<div data-slot="row">
<ui-carousel-previous>
<button aria-label="Previous slide">${createElement(ChevronLeft, { "aria-hidden": "true" }).outerHTML}</button>
</ui-carousel-previous>
<ui-carousel-viewport>
<ui-carousel-content>
${photos.map((photo) => `<ui-carousel-item><div data-slot="tile">${photo.name}</div></ui-carousel-item>`).join("")}
</ui-carousel-content>
</ui-carousel-viewport>
<ui-carousel-next>
<button aria-label="Next slide">${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}</button>
</ui-carousel-next>
</div>
</ui-carousel>
</div>
`
const carousel = root.querySelector("ui-carousel")!
root.querySelector("ui-select")!.addEventListener("valuechange", (event) => {
if (event.detail.value) {
carousel.setAttribute("align", String(event.detail.value))
}
})
}
export { mount }默认页
default-page 是非受控时轮播起始的页。默认是 1。
import "@ui-sdk/web/carousel"
import { ChevronLeft, ChevronRight, createElement } from "lucide"
const slides = [1, 2, 3, 4, 5]
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-carousel aria-label="Featured" default-page="3">
<div data-slot="row">
<ui-carousel-previous>
<button aria-label="Previous slide">${createElement(ChevronLeft, { "aria-hidden": "true" }).outerHTML}</button>
</ui-carousel-previous>
<ui-carousel-viewport>
<ui-carousel-content>
${slides.map((slide) => `<ui-carousel-item><div data-slot="tile">${slide}</div></ui-carousel-item>`).join("")}
</ui-carousel-content>
</ui-carousel-viewport>
<ui-carousel-next>
<button aria-label="Next slide">${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}</button>
</ui-carousel-next>
</div>
</ui-carousel>
`
}
export { mount }指示器
指示器是一个选项卡列表:当前页只有一个 Tab 停靠点,方向键在它们之间移动并显示对应的页,Home 和 End 跳到两端。每个指示器控制它那一页的幻灯片。
每张幻灯片写一个。超出页数的指示器会隐藏自己,所以同一份标记在任意数量的幻灯片下都能用。指示器的 page 从它们的顺序推断;传入它,才能在服务端渲染出选中的那个。
import "@ui-sdk/web/carousel"
const photos = [
{ name: "Dunes" },
{ name: "Forest" },
{ name: "Glacier" },
{ name: "Canyon" },
{ name: "Meadow" },
{ name: "Harbor" },
]
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-carousel aria-label="Photos">
<ui-carousel-viewport>
<ui-carousel-content>
${photos.map((photo) => `<ui-carousel-item><div data-slot="tile">${photo.name}</div></ui-carousel-item>`).join("")}
</ui-carousel-content>
</ui-carousel-viewport>
<ui-carousel-indicator-group aria-label="Choose a photo">
${photos.map((photo) => `<ui-carousel-indicator><button aria-label="${photo.name}"></button></ui-carousel-indicator>`).join("")}
</ui-carousel-indicator-group>
</ui-carousel>
`
}
export { mount }页
slides-per-page 是一页放多少张幻灯片:Next 每次移动这么多,每个指示器也代表这么多。"auto" 按能显示的数量来放。无法从起始位置排满的页,比如最后几张幻灯片,会并入最后一页。在显示三张幻灯片的情况下,五张幻灯片按每页一张算有三页,按每页三张算有两页。
import "@ui-sdk/web/carousel"
import { ChevronLeft, ChevronRight, createElement } from "lucide"
const products = [1, 2, 3, 4, 5, 6, 7, 8]
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-carousel aria-label="Products" slides-per-page="3">
<div data-slot="row">
<ui-carousel-previous>
<button aria-label="Previous page">${createElement(ChevronLeft, { "aria-hidden": "true" }).outerHTML}</button>
</ui-carousel-previous>
<ui-carousel-viewport>
<ui-carousel-content>
${products.map((product) => `<ui-carousel-item><div data-slot="tile">${product}</div></ui-carousel-item>`).join("")}
</ui-carousel-content>
</ui-carousel-viewport>
<ui-carousel-next>
<button aria-label="Next page">${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}</button>
</ui-carousel-next>
</div>
<div data-slot="row">
<ui-carousel-indicator-group aria-label="Choose a page">
${products.map((product) => `<ui-carousel-indicator><button aria-label="Page ${product}"></button></ui-carousel-indicator>`).join("")}
</ui-carousel-indicator-group>
</div>
</ui-carousel>
`
}
export { mount }缩略图
图库和一条缩略图带共享选中的页。缩略图轮播用 drag-free 自由滚动,按能显示的数量来放。按压缩略图会选中它的幻灯片。
import "@ui-sdk/web/carousel"
const photos = [
{ name: "Dunes" },
{ name: "Forest" },
{ name: "Glacier" },
{ name: "Canyon" },
{ name: "Meadow" },
{ name: "Harbor" },
]
function mount(root: HTMLElement) {
root.innerHTML = `
<div data-slot="stack">
<ui-carousel aria-label="Photos">
<ui-carousel-viewport>
<ui-carousel-content>
${photos.map((photo) => `<ui-carousel-item><div data-slot="tile">${photo.name}</div></ui-carousel-item>`).join("")}
</ui-carousel-content>
</ui-carousel-viewport>
</ui-carousel>
<ui-carousel aria-label="Thumbnails" drag-free slides-per-page="auto">
<ui-carousel-viewport>
<ui-carousel-content>
${photos.map((photo, index) => `<ui-carousel-item aria-label="${photo.name}"><button type="button" data-page="${index + 1}" aria-pressed="${index === 0}">${photo.name}</button></ui-carousel-item>`).join("")}
</ui-carousel-content>
</ui-carousel-viewport>
</ui-carousel>
</div>
`
const gallery = root.querySelector("ui-carousel")!
const thumbnails = [
...root.querySelectorAll<HTMLButtonElement>("button[data-page]"),
]
const show = (page: number) => {
for (const thumbnail of thumbnails) {
thumbnail.setAttribute(
"aria-pressed",
String(thumbnail.dataset.page === String(page))
)
}
thumbnails[page - 1]?.scrollIntoView({
block: "nearest",
inline: "nearest",
})
}
for (const thumbnail of thumbnails) {
thumbnail.addEventListener(
"click",
() => (gallery.page = Number(thumbnail.dataset.page))
)
}
gallery.addEventListener("pagechange", (event) => show(event.detail.value))
}
export { mount }自动轮播
default-playing 让轮播开始自动播放,每隔 interval 毫秒换一页(默认 5000)。ui-carousel-play-toggle 启动和停止它。轮播期间它的按钮带有 data-playing,所以名称可以用 CSS 切换。
按照轮播模式的要求,键盘焦点移入时轮播停止,在用户要求之前不会重新开始,鼠标悬停时也会暂停。标签页隐藏、轮播滚出视野以及手指按住期间,它同样会暂停。自己切换幻灯片会停止轮播。只有不在轮播时,幻灯片才是礼貌的实时区域(polite live region),所以屏幕阅读器不会每隔几秒被打断。用户偏好减少动态效果时,它不会自行开始。
根上的 --carousel-interval 是间隔,暂停期间带有 data-paused,所以进度条可以用 CSS 自己计时。
import "@ui-sdk/web/carousel"
import { ChevronLeft, ChevronRight, createElement } from "lucide"
import { log } from "./log"
const photos = [
{ name: "Dunes" },
{ name: "Forest" },
{ name: "Glacier" },
{ name: "Canyon" },
{ name: "Meadow" },
{ name: "Harbor" },
]
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-carousel aria-label="Photos" default-playing interval="4000">
<div data-slot="controls">
<ui-carousel-play-toggle>
<button><span data-show="playing">Pause</span><span data-show="stopped">Play</span></button>
</ui-carousel-play-toggle>
</div>
<div data-slot="row">
<ui-carousel-previous>
<button aria-label="Previous slide">${createElement(ChevronLeft, { "aria-hidden": "true" }).outerHTML}</button>
</ui-carousel-previous>
<ui-carousel-viewport>
<ui-carousel-content>
${photos.map((photo) => `<ui-carousel-item><div data-slot="tile">${photo.name}</div></ui-carousel-item>`).join("")}
</ui-carousel-content>
</ui-carousel-viewport>
<ui-carousel-next>
<button aria-label="Next slide">${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}</button>
</ui-carousel-next>
</div>
</ui-carousel>
`
root
.querySelector("ui-carousel")!
.addEventListener("playingchange", (event) => {
log(
root,
`${event.detail.value ? "Playing" : "Stopped"} (${event.detail.reason})`
)
})
}
export { mount }进度
根上的 --carousel-progress 表示幻灯片滚动了多远,从第一页的 0 到最后一页的 1,在滚动或弹簧动画的每一帧更新,不会引起重新渲染,所以进度条可以用 CSS 跟随它。启用 loop 时,它从 0 走到 1 再回到 0。控制器的 getProgress() 读取同一个数字。
每张幻灯片都有自己的 --carousel-item-progress,它的页停稳时是 0。幻灯片位于前方一页时,它向 1 上升;位于后方一页时,它向 -1 下降,所以幻灯片可以在进出时用 CSS 淡入淡出、缩放或倾斜。用 var(--carousel-item-progress, 0) 读取它,这样首次绘制时也有值。
pagechangecomplete 在幻灯片停稳到某一页后触发,无论是弹簧动画、拖动还是滚动之后,页在 event.detail.value 里。把会让动画卡顿的工作放在这里,比如加载后面幻灯片的图片。
import "@ui-sdk/web/carousel"
import { ChevronLeft, ChevronRight, createElement } from "lucide"
import { log } from "./log"
const slides = [1, 2, 3, 4, 5]
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-carousel aria-label="Featured">
<div data-slot="row">
<ui-carousel-previous>
<button aria-label="Previous slide">${createElement(ChevronLeft, { "aria-hidden": "true" }).outerHTML}</button>
</ui-carousel-previous>
<ui-carousel-viewport>
<ui-carousel-content>
${slides.map((slide) => `<ui-carousel-item><div data-slot="tile">${slide}</div></ui-carousel-item>`).join("")}
</ui-carousel-content>
</ui-carousel-viewport>
<ui-carousel-next>
<button aria-label="Next slide">${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}</button>
</ui-carousel-next>
</div>
<div data-slot="row">
<div data-slot="bar">
<div></div>
</div>
</div>
</ui-carousel>
`
root
.querySelector("ui-carousel")!
.addEventListener("pagechangecomplete", (event) => {
log(root, `Rested on slide ${event.detail.value}`)
})
}
export { mount }受控
元素自己持有它的页,从 1 开始。page property 读取它,给它赋值会翻到那一页。监听 pagechange,新页在 event.detail.value 里。在幻灯片测量完成之前,api.getPageCount() 为 null。
每次变更都带一个原因:next-press 和 previous-press 来自这些部件,item-press 来自指示器或露出的幻灯片,list-navigation 来自方向键,swipe 来自手指或鼠标拖动,scroll 来自滚轮或触控板,timeout 来自轮播,imperative 来自控制器。调用 event.preventDefault() 留在当前页:滑动或拖动会弹回。
import "@ui-sdk/web/carousel"
import { ChevronLeft, ChevronRight, createElement } from "lucide"
import { log } from "./log"
const slides = [1, 2, 3, 4, 5]
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-carousel aria-label="Featured">
<div data-slot="row">
<ui-carousel-previous>
<button aria-label="Previous slide">${createElement(ChevronLeft, { "aria-hidden": "true" }).outerHTML}</button>
</ui-carousel-previous>
<ui-carousel-viewport>
<ui-carousel-content>
${slides.map((slide) => `<ui-carousel-item><div data-slot="tile">${slide}</div></ui-carousel-item>`).join("")}
</ui-carousel-content>
</ui-carousel-viewport>
<ui-carousel-next>
<button aria-label="Next slide">${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}</button>
</ui-carousel-next>
</div>
</ui-carousel>
`
root.querySelector("ui-carousel")!.addEventListener("pagechange", (event) => {
log(root, `Page ${event.detail.value} (${event.detail.reason})`)
})
}
export { mount }从任何地方翻页
元素的 api property 就是它的控制器。Previous、Next、指示器组和播放切换按钮可以用 for="<carousel id>" 放在页面上的任何地方,比如放在区块标题里。
drag="false" 关闭滑动和拖动,所以只有部件、按键和控制器能移动它。
import "@ui-sdk/web/carousel"
import { ChevronLeft, ChevronRight, createElement } from "lucide"
const slides = [1, 2, 3, 4, 5]
function mount(root: HTMLElement) {
root.innerHTML = `
<div data-slot="stack">
<div data-slot="controls">
<ui-carousel-previous for="featured-carousel">
<button aria-label="Previous slide">${createElement(ChevronLeft, { "aria-hidden": "true" }).outerHTML}</button>
</ui-carousel-previous>
<ui-carousel-next for="featured-carousel">
<button aria-label="Next slide">${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}</button>
</ui-carousel-next>
<button type="button" data-show-last>Show the Last Slide</button>
</div>
<ui-carousel id="featured-carousel" aria-label="Featured" drag="false">
<ui-carousel-viewport>
<ui-carousel-content>
${slides.map((slide) => `<ui-carousel-item><div data-slot="tile">${slide}</div></ui-carousel-item>`).join("")}
</ui-carousel-content>
</ui-carousel-viewport>
</ui-carousel>
</div>
`
const carousel = root.querySelector("ui-carousel")!
root
.querySelector("[data-show-last]")!
.addEventListener("click", () => carousel.api.setPage(5))
}
export { mount }滑动与拖动
触摸、触控板和滚轮以原生方式滚动视口,翻页由 CSS 滚动吸附完成。原生滚动和吸附在 JavaScript 加载之前也能工作。鼠标或触控笔也可以拖动幻灯片:它们跟随指针,越过两端时被拉伸,然后按松开时的速度弹到一次快速甩动会到达的页。真正移动过的拖动不会点击它起始位置上的链接,幻灯片里的字段仍然接收指针事件。按压边缘露出的幻灯片会翻到它那一页。
没有设置 skip-snaps 时,一次滑动最多移动一页。drag-free 让滑动一路滑到停下为止,最近的页成为当前页。
按钮、按键、指示器、轮播和控制器会让滚动位置产生动画。在移动过程中再次按压会更新目标位置。减少动态效果会让这些变更立即生效。
关闭轮播
disabled 暂时关掉轮播,比如在宽屏上,同样的幻灯片会排成网格。各部件会去掉自己的角色、幻灯片名称和内联样式,每张幻灯片仍然可以到达,视口不再响应按键和滑动翻页,Previous、Next、指示器和播放切换按钮都会隐藏。重新打开后,它会再次测量幻灯片并显示当前页。
<ui-carousel aria-label="Featured products">
<!-- Viewport, slides and controls. -->
</ui-carousel>
<script type="module">
const carousel = document.querySelector("ui-carousel")
const isWide = matchMedia("(min-width: 768px)")
const follow = () => carousel.toggleAttribute("disabled", isWide.matches)
isWide.addEventListener("change", follow)
follow()
</script>用标记提供幻灯片
每张幻灯片都是一个 <ui-carousel-item>。当卡片以标记的形式到来时,比如服务器或 CMS 渲染的列表,把每张卡片放进一个 <ui-carousel-item> 里:
<ui-carousel-content>
<ui-carousel-item><article class="card">…</article></ui-carousel-item>
<ui-carousel-item><article class="card">…</article></ui-carousel-item>
</ui-carousel-content>无法修改标记时,用脚本把卡片包进 <ui-carousel-item> 里。轮播会把每个新项当作一张幻灯片来测量:
const content = document.querySelector("ui-carousel-content")
for (const card of content.querySelectorAll(":scope > .card")) {
const item = document.createElement("ui-carousel-item")
card.replaceWith(item)
item.append(card)
}自定义渲染
元素没有渲染函数。根据它们的属性设置样式,并观察这些属性来改变它们里面的内容:幻灯片的 data-active 和 data-in-view,翻页按钮的 data-disabled,指示器的 data-selected,播放切换按钮的 data-playing 和 data-paused。这里每张幻灯片会说明自己何时显示,Next 的按钮带上 data-disabled 后,一个图库链接会取代 Next 的位置。
import "@ui-sdk/web/carousel"
import { ChevronLeft, ChevronRight, createElement } from "lucide"
const photos = [
{ name: "Dunes" },
{ name: "Forest" },
{ name: "Glacier" },
{ name: "Canyon" },
{ name: "Meadow" },
{ name: "Harbor" },
]
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-carousel aria-label="Photos">
<ui-carousel-viewport>
<ui-carousel-content>
${photos.map((photo, index) => `<ui-carousel-item><div data-slot="tile">${photo.name}<span data-slot="hint">${index + 1} / ${photos.length}<span hidden> · showing</span></span></div></ui-carousel-item>`).join("")}
</ui-carousel-content>
</ui-carousel-viewport>
<div data-slot="row">
<ui-carousel-previous>
<button>${createElement(ChevronLeft, { "aria-hidden": "true" }).outerHTML} Previous</button>
</ui-carousel-previous>
<ui-carousel-next>
<button>Next ${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}</button>
</ui-carousel-next>
<a href="https://example.com/gallery" hidden>See all photos</a>
</div>
</ui-carousel>
`
const carousel = root.querySelector("ui-carousel")!
const next = root.querySelector<HTMLElement>("ui-carousel-next button")!
const link = root.querySelector("a")!
const update = () => {
for (const item of carousel.querySelectorAll("ui-carousel-item")) {
item.querySelector<HTMLElement>("[data-slot='hint'] > span")!.hidden =
!item.hasAttribute("data-active")
}
const end = next.hasAttribute("data-disabled")
const focused = document.activeElement === next
link.hidden = !end
if (end && focused) {
link.focus()
}
next.hidden = end
}
new MutationObserver(update).observe(carousel, {
subtree: true,
attributeFilter: ["data-active", "data-disabled"],
})
update()
}
export { mount }样式
在到达两端时给 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,它的状态属性列在数据属性下。
<ui-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. |
<ui-carousel-content>
| 变量 | 内容 |
|---|---|
--carousel-display | Set it yourself: how the content lays out its slides, like grid. Flex by default. |
<ui-carousel-item>
| 变量 | 内容 |
|---|---|
--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. |
数据属性
<ui-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. |
<ui-carousel-viewport>
[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. |
<ui-carousel-content>
[data-slot="carousel-content"]
| 属性 | 含义 |
|---|---|
data-orientation | horizontalverticalWhich way the slides scroll, and which arrow keys page. |
<ui-carousel-item>
[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. |
<ui-carousel-previous>
[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. |
<ui-carousel-indicator>
[data-slot="carousel-indicator"]
| 属性 | 含义 |
|---|---|
data-selected | Present on the current page's indicator, beside aria-selected. |
<ui-carousel-play-toggle>
[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 参考
属性以 kebab 命名,比如 default-page、slides-per-page 和 default-playing,数字就是数字。controller 是 property。page 和 playing 是 live property。回调是 DOM 事件。
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.
pagechange event- Runs when the page wants to change.
details.reasonsays why, anddetails.cancel()stays on the page. pagechangecomplete event- 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.
playingchange event- 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
滚动的区域。<ui-carousel-viewport> 原生滚动和吸附,并为方向键接收焦点。
CarouselContent
容纳幻灯片。<ui-carousel-content> 播报进入视野的幻灯片,轮播时除外。
CarouselItem
一张幻灯片。<ui-carousel-item> 带 group 角色,按位置命名,比如“2 of 5”。
CarouselPrevious
controller?object- The carousel this part drives when it isn't inside one, like buttons in a page header.
CarouselNext
显示下一页。<ui-carousel-next> 接受与 <ui-carousel-previous> 相同的属性。
CarouselIndicatorGroup
把指示器分组。<ui-carousel-indicator-group> 带 tablist 角色,并接受与 <ui-carousel-previous> 相同的属性。
CarouselIndicator
page?number- The page it shows and selects, from 1. Inferred from the indicators' order when left out.
CarouselPlayToggle
启动和停止轮播。<ui-carousel-play-toggle> 包住一个 button,并接受与 <ui-carousel-previous> 相同的属性。
状态
同一份状态会作为属性显示在每个部件上。
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.
原因
event.detail.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.
控制器
元素的 api property 有相同的方法。
每个写入方法都接受一个可选的 { 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.
事件
事件在各自的元素上触发,不冒泡,新值在 event.detail.value 里,reason 和 event 就在旁边。调用 preventDefault() 会取消这次变更。要获得类型化的监听器,把元素标注为 UiCarouselElement。
| 成员 | 所属 | 说明 |
|---|---|---|
page property | ui-carousel | 当前页。给它赋值会翻到那一页 |
playing property | ui-carousel | 是否在轮播 |
api property | ui-carousel | 控制器 |
controller property | ui-carousel | 来自 createCarouselController() 的控制器 |
pagechange event | ui-carousel | detail: { value: page, reason, event, source } |
pagechangecomplete event | ui-carousel | detail: { value: page },在幻灯片停稳后 |
playingchange event | ui-carousel | detail: { value: playing, reason, event, source } |
无障碍
它遵循 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。