实现效果如下 不管是点击还是 滚动鼠标 顶部的样式也会跟随变化
点击会跳转到指定的位置
通过IntersectionObserver 监听是否可见
下面代码可以直接执行到vue的文件
<template>
<div>
<ul class="nav">
<li v-for="tab in tabs" :key="tab.name" :class="{ active: currentTab === tab.name }" @click="scrollToTab(tab)">
{{ tab.label }}
</li>
<div class="underline" :style="underlineStyle"></div>
</ul>
<div class="section" id="section1">Section 1</div>
<div class="section" id="section2">Section 2</div>
<div class="section" id="section3">Section 3</div>
<div class="section" id="section4">Section 4</div>
<div class="section" id="section5">Section 5</div>
</div>
</template>
<script>
export default {
data () {
return {
currentTab: 'tab1',
tabs: [
{ name: 'tab1', label: '首页', id: 'section1' },
{ name: 'tab2', label: '服务内容', id: 'section2' },
{ name: 'tab3', label: '业务案例', id: 'section3' },
{ name: 'tab4', label: '关于我们', id: 'section4' },
{ name: 'tab5', label: '联系方式', id: 'section5' }
],
underlineStyle: {
width: '0px',
left: '0px'
}
}
},
methods: {
scrollToTab (section) {
this.currentTab = section.name
this.updateUnderline()
const element = document.getElementById(section.id)
document.getElementById(section.id).scrollIntoView({ behavior: 'smooth', block: 'center' })
},
updateUnderline () {
this.$nextTick(() => {
const activeTab = this.$el.querySelector('.nav .active')
if (activeTab) {
this.underlineStyle.width = `${activeTab.offsetWidth}px`
this.underlineStyle.left = `${activeTab.offsetLeft}px`
}
})
},
handleIntersection (entries) {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const tab = this.tabs.find((tab) => tab.id === entry.target.id)
if (tab) {
this.currentTab = tab.name
this.updateUnderline()
}
}
})
}
},
mounted () {
this.updateUnderline()
const options = {
root: null,
rootMargin: `-${this.$el.querySelector('.nav').offsetHeight}px 0px 0px 0px`,
threshold: 0.5
}
const observer = new IntersectionObserver(this.handleIntersection, options)
this.tabs.forEach((tab) => {
const section = document.getElementById(tab.id)
if (section) {
observer.observe(section)
}
})
window.addEventListener('resize', this.updateUnderline)
},
beforeDestroy () {
window.removeEventListener('resize', this.updateUnderline)
}
}
</script>
<style scoped>
.nav {
display: flex;
position: fixed;
top: 0;
width: 1000px;
background-color: white;
z-index: 1000;
border-bottom: 1px solid #ccc;
}
.nav li {
flex: 1;
text-align: center;
padding: 10px;
cursor: pointer;
position: relative;
}
.nav li.active {
color: blue;
}
.underline {
position: absolute;
bottom: 0;
height: 2px;
background-color: blue;
transition: width 0.3s, left 0.3s;
}
.section {
height: 300px;
padding-top: 60px; /* 留出导航栏的高度 */
border-bottom: 1px solid #ccc;
}
</style>