57 lines
2.5 KiB
Vue
57 lines
2.5 KiB
Vue
<template>
|
||
<nav class="aa-anchor" :class="{ fixed }">
|
||
<template v-for="(it, i) in items" :key="it.key">
|
||
<button class="aa-anchor-item" :class="{ 'is-active': active === it.key }" @click="go(it.key)">{{ it.label }}</button>
|
||
<div v-if="it.children" class="aa-anchor-sub">
|
||
<button
|
||
v-for="c in it.children" :key="c.key"
|
||
class="aa-anchor-item" :class="{ 'is-active': active === c.key }"
|
||
@click="go(c.key)"
|
||
>{{ c.label }}</button>
|
||
</div>
|
||
</template>
|
||
</nav>
|
||
</template>
|
||
|
||
<script setup>
|
||
import { ref, onMounted, onBeforeUnmount } from 'vue';
|
||
|
||
const props = defineProps({
|
||
items: { type: Array, required: true }, // [{ key, label, children? }](key 对应页面元素 id)
|
||
fixed: { type: Boolean, default: false },
|
||
offset: { type: Number, default: 24 } // 滚动偏移(避开吸顶高度)
|
||
});
|
||
|
||
const active = ref(props.items[0] ? props.items[0].key : '');
|
||
const allKeys = [];
|
||
(function collect(list) { list.forEach(i => { allKeys.push(i.key); if (i.children) collect(i.children); }); })(props.items);
|
||
|
||
function go(key) {
|
||
const el = document.getElementById(key);
|
||
if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - props.offset, behavior: 'smooth' });
|
||
}
|
||
function onScroll() {
|
||
const pos = window.scrollY + 80;
|
||
let cur = allKeys[0];
|
||
for (const k of allKeys) {
|
||
const el = document.getElementById(k);
|
||
if (el && el.offsetTop <= pos) cur = k;
|
||
}
|
||
active.value = cur;
|
||
}
|
||
onMounted(() => window.addEventListener('scroll', onScroll));
|
||
onBeforeUnmount(() => window.removeEventListener('scroll', onScroll));
|
||
</script>
|
||
|
||
<!-- 样式对齐 组件7.txt AnchorNav 规范 -->
|
||
<style scoped>
|
||
.aa-anchor { font-family: var(--font-family, -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif); width: 160px; }
|
||
.aa-anchor.fixed { position: fixed; right: 24px; top: 80px; }
|
||
.aa-anchor-item { display: block; padding: 6px 12px; font-size: 13px; color: #8C8C8C; cursor: pointer; border-left: 2px solid #E8ECF1; line-height: 1.4; transition: color .15s, border-color .15s; background: none; border-top: none; border-right: none; border-bottom: none; text-align: left; width: 100%; }
|
||
.aa-anchor-item:hover { color: #2F54EB; }
|
||
.aa-anchor-item.is-active { color: #2F54EB; border-left-color: #2F54EB; font-weight: 500; }
|
||
.aa-anchor-sub { padding-left: 8px; }
|
||
.aa-anchor-sub .aa-anchor-item { border-left: none; padding-left: 20px; }
|
||
.aa-anchor-sub .aa-anchor-item.is-active { border-left: 2px solid #2F54EB; }
|
||
</style>
|