64 lines
2.7 KiB
Plaintext
64 lines
2.7 KiB
Plaintext
<template>
|
||
<nav class="kole-anchor" :class="{ fixed }">
|
||
<!-- Vue 2 不允许在 <template v-for> 上写 :key,key 必须落在真实元素上 -->
|
||
<template v-for="(it, i) in items">
|
||
<button :key="'item-' + it.key" class="kole-anchor-item" :class="{ 'is-active': active === it.key }" @click="go(it.key)">{{ it.label }}</button>
|
||
<div v-if="it.children" :key="'sub-' + it.key" class="kole-anchor-sub">
|
||
<button
|
||
v-for="c in it.children" :key="c.key"
|
||
class="kole-anchor-item" :class="{ 'is-active': active === c.key }"
|
||
@click="go(c.key)"
|
||
>{{ c.label }}</button>
|
||
</div>
|
||
</template>
|
||
</nav>
|
||
</template>
|
||
|
||
<script>
|
||
export default {
|
||
name: 'KoleAnchorNav',
|
||
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>
|
||
.kole-anchor { font-family: var(--font-family, -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif); width: 160px; }
|
||
.kole-anchor.fixed { position: fixed; right: 24px; top: 80px; }
|
||
.kole-anchor-item { display: block; padding: 6px 12px; font-size: 13px; color: #6E6E6E; 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%; }
|
||
.kole-anchor-item:hover { color: #2F54EB; }
|
||
.kole-anchor-item.is-active { color: #2F54EB; border-left-color: #2F54EB; font-weight: 500; }
|
||
.kole-anchor-sub { padding-left: 8px; }
|
||
.kole-anchor-sub .kole-anchor-item { border-left: none; padding-left: 20px; }
|
||
.kole-anchor-sub .kole-anchor-item.is-active { border-left: 2px solid #2F54EB; }
|
||
</style>
|