一、html
<div ref="computingref"><section id="section1"> </section><section id="section2"> </section><section id="section3"> </section>
</div><div class="nav-list" v-if="activeHash"><!-- <el-tabs:tab-position="'right'"v-model="activeHash"@tab-change="scrollTo"><el-tab-panev-for="(item, index) in anchorList":key="index":label="item.label" :name="item.value"></el-tab-pane></el-tabs> --><el-timeline style="width: 245px"><el-timeline-itemv-for="(activity, index) in anchorList":key="index":type="activeHash == activity.value?'primary':''":hollow="activeHash != activity.value"><spanclass="timelineclass":style="activeHash == activity.value?'color:#eb682c':''"@click="scrollTo(activity.value)">{{ activity.label }}</span></el-timeline-item></el-timeline></div>
二、js
// 常量定义
const computingref = ref();
const anchorList = ref([{label:'xxxxx',value:'#section1'},{label:'xxxxxxx',value:'#section2'},{label:'xxxxxxxxxxx',value:'#section3'}
])// 响应式数据
const activeHash = ref('');
const offsets = ref([]);// 计算锚点偏移量
const calculateOffsets = () => {offsets.value = anchorList.value.map(e=>{const element = document.querySelector(e.value)return element.offsetTop - 300 // 上偏移多少})
};// 更新激活的 hash
const updateActiveHash = () => {const scrollTop = computingref.value?.scrollTop || 0const findtops = offsets.value.filter(offset => scrollTop > offset);activeHash.value = findtops.length > 0 ? `#section${findtops.length}` : '';
};// 滚动到指定锚点
const scrollTo = (hash) => {activeHash.value = hashconst target = document.querySelector(hash);if (target) {const offset = target.offsetTop// window.scrollTo(0, offset);if(computingref.value) computingref.value.scrollTop = offset}
};const handleContainerScroll = () => {updateActiveHash()
}// 生命周期钩子
onMounted(() => {nextTick(() => {calculateOffsets();});
});