63 lines
2.5 KiB
Vue
63 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>
|
|
export default {
|
|
name: 'AaAnchorNav',
|
|
props: {
|
|
items: { type: Array, required: true }, // [{ key, label, children? }]
|
|
fixed: { type: Boolean, default: false },
|
|
offset: { type: Number, default: 24 }
|
|
},
|
|
data() { return { active: this.items[0] ? this.items[0].key : '' }; },
|
|
computed: {
|
|
allKeys() {
|
|
const out = [];
|
|
(function collect(list) { list.forEach(i => { out.push(i.key); if (i.children) collect(i.children); }); })(this.items);
|
|
return out;
|
|
}
|
|
},
|
|
methods: {
|
|
go(key) {
|
|
const el = document.getElementById(key);
|
|
if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - this.offset, behavior: 'smooth' });
|
|
},
|
|
onScroll() {
|
|
const pos = window.scrollY + 80;
|
|
let cur = this.allKeys[0];
|
|
for (const k of this.allKeys) {
|
|
const el = document.getElementById(k);
|
|
if (el && el.offsetTop <= pos) cur = k;
|
|
}
|
|
this.active = cur;
|
|
}
|
|
},
|
|
mounted() { window.addEventListener('scroll', this.onScroll); },
|
|
beforeDestroy() { window.removeEventListener('scroll', this.onScroll); }
|
|
};
|
|
</script>
|
|
|
|
<!-- 样式对齐 组件7.txt AnchorNav 规范 -->
|
|
<style>
|
|
.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>
|