Anchor 锚点
页面内锚点导航 + 滚动联动高亮。<nav> 语义 + aria-current="location"。
基础用法
基础用法
vue
<script setup>
const anchorItems = [
{ id: 'sec-1', title: '第一节' },
{ id: 'sec-2', title: '第二节', children: [{ id: 'sec-2-1', title: '第二节之一' }] },
]
</script>
<template>
<LhAnchor :items="anchorItems" />
</template>vue
<script>
export default {
data() {
return {
anchorItems: [
{ id: 'sec-1', title: '第一节' },
{ id: 'sec-2', title: '第二节', children: [{ id: 'sec-2-1', title: '第二节之一' }] },
],
}
},
}
</script>
<template>
<LhAnchor :items="anchorItems" />
</template>横向排列与滚动选项
direction="horizontal" 切换横向排列;smooth 关闭平滑滚动;offset 补偿锚点区域相对滚动容器顶部的偏移;target 监听指定滚动容器(默认 window)。
横向锚点
vue
<script setup>
const anchorItems = [
{ id: 'sec-1', title: '第一节' },
{ id: 'sec-2', title: '第二节' },
]
</script>
<template>
<!-- 横向锚点 -->
<LhAnchor
:items="anchorItems"
direction="horizontal"
:offset="8"
:smooth="true"
/>
</template>vue
<script>
export default {
data() {
return {
anchorItems: [
{ id: 'sec-1', title: '第一节' },
{ id: 'sec-2', title: '第二节' },
],
}
},
}
</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[]
/** 滚动容器(选择器或元素,默认 window) */
target?: string | HTMLElement
/** 锚点区域相对滚动容器顶部的偏移(用于联动判定) */
offset?: number
/** 排列方向 */
direction?: 'vertical' | 'horizontal'
/** 平滑滚动 */
smooth?: boolean
/** sx 快速布局属性 */
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 */
id: string
/** 显示文本 */
title: string
/** 子级锚点 */
children?: LhAnchorItem[]
}