Anchor アンカー
ページ内のアンカーナビゲーションと、スクロール連動ハイライトを提供します。<nav> セマンティックと aria-current="location" を備えます。
基本的な使い方
基本的な使い方
vue
<script setup>
const anchorItems = [
{ id: 'sec-1', title: '第 1 節' },
{ id: 'sec-2', title: '第 2 節', children: [{ id: 'sec-2-1', title: '第 2 節の 1' }] },
]
</script>
<template>
<LhAnchor :items="anchorItems" />
</template>vue
<script>
export default {
data() {
return {
anchorItems: [
{ id: 'sec-1', title: '第 1 節' },
{ id: 'sec-2', title: '第 2 節', children: [{ id: 'sec-2-1', title: '第 2 節の 1' }] },
],
}
},
}
</script>
<template>
<LhAnchor :items="anchorItems" />
</template>横並びとスクロールオプション
direction="horizontal" で横並びに切り替えます。smooth でスムーズスクロールをオフにします。offset でアンカー領域のスクロールコンテナ上端からのオフセットを補正します。target で監視するスクロールコンテナを指定します(デフォルトは window)。
横並びのアンカー
vue
<script setup>
const anchorItems = [
{ id: 'sec-1', title: '第 1 節' },
{ id: 'sec-2', title: '第 2 節' },
]
</script>
<template>
<!-- 横並びのアンカー -->
<LhAnchor
:items="anchorItems"
direction="horizontal"
:offset="8"
:smooth="true"
/>
</template>vue
<script>
export default {
data() {
return {
anchorItems: [
{ id: 'sec-1', title: '第 1 節' },
{ id: 'sec-2', title: '第 2 節' },
],
}
},
}
</script>
<template>
<!-- 横並びのアンカー -->
<LhAnchor
:items="anchorItems"
direction="horizontal"
:offset="8"
:smooth="true"
/>
</template>API
LhAnchor Props
| プロパティ名 | 説明 | 型 | デフォルト値 |
|---|---|---|---|
| items | アンカーデータ(子階層をサポート) | [LhAnchorItem](#type-LhAnchorItem)[] | — |
| target | スクロールコンテナ(セレクターまたは要素、デフォルトは window) | string | HTMLElement | — |
| offset | アンカー領域のスクロールコンテナ上端からのオフセット(連動判定に使用) | number | 0 |
| direction | 並ぶ方向 | "vertical" | "horizontal" | 'vertical' |
| smooth | スムーズスクロール | boolean | true |
| sx | sx クイックレイアウトプロパティ | LhSxProps | — |
Events
| イベント名 | 説明 | コールバック |
|---|---|---|
| change | 現在アクティブなアンカーが変化したときに発火します(スクロール連動またはアンカークリック) | (id: string) |
| click | アンカーリンクをクリックしたときに発火します(スクロールによるジャンプより先に送出されます) | (event: MouseEvent, id: string) |
LhAnchorItem
| フィールド | 説明 | 型 |
|---|---|---|
| id | 対象要素の id | string |
| title | 表示テキスト | string |
| children | 子アンカー | LhAnchorItem[] |
アクセシビリティ
- コンテナはセマンティックな
<nav>でaria-labelを持ちます。現在のアンカーにはaria-current="location"を付けます - リンクは本物の
<a href="#id">です(JS なしでもジャンプ可能。クリック時にスムーズスクロールへ拡張されます) - スムーズスクロールは
prefers-reduced-motion: reduceの環境では自動的に即時ジャンプにダウングレードされます
型定義
このコンポーネントが外部にエクスポートする TypeScript の型構造を以下に示します(packages/components/anchor/src/types.ts および @lh-ui/share/core/* のソースから自動抽出。各エントリーをクリックすると完全な定義が表示されます。プロパティの説明は上の Props 表を参照してください):
LhAnchorProps
ts
export interface LhAnchorProps {
items: LhAnchorItem[]
target?: string | HTMLElement
offset?: number
direction?: 'vertical' | 'horizontal'
smooth?: boolean
sx?: LhSxProps
}LhFlatAnchorItem (@lh-ui/share/core/anchor より)
ts
export interface LhFlatAnchorItem {
id: string
title: string
level: number
}LhAnchorItem (@lh-ui/share/core/anchor より)
ts
export interface LhAnchorItem {
id: string
title: string
children?: LhAnchorItem[]
}