项目场景:
- 点击导航到达相应的位置 --滚动页面导航到达相应的样式
问题描述:
点击导航页面到达相应锚点的高度
+ 导航
<div class="anchor">
<a :class="activeName === 'first' ? 'isActive' : ''" @click="clickScroll('first')">基础信息</a>
<a :class="activeName === 'second' ? 'isActive' : ''" @click="clickScroll('second')">销售信息</a>
<a :class="activeName === 'third' ? 'isActive' : ''" @click="clickScroll('third')">图文描述</a>
<a :class="activeName === 'fourth' ? 'isActive' : ''" @click="clickScroll('fourth')">SEO设置</a>
</div>
+ 导航样式
.anchor {
position: fixed;
top: 230px;
width: calc(100% - 253px);
background: #fff;
border-bottom: 2px solid #e4e7ed;
font-size: 16px;
color: #aaa;
font-weight: bold;
z-index: 999;
a {
display: inline-block;
width: 120px;
position: relative;
top: 2px;
padding-bottom: 10px;
text-align: center;
}
.isActive {
color: #02a7f0;
border-bottom: 2px solid #02a7f0;
}
}
<h3 id="first" class="h3-title" style="margin-top: 60px;">基础信息</h3>
<h3 id="second" class="h3-title">销售信息</h3>
<h3 id="third" class="h3-title">图文描述</h3>
<h3 id="fourth" class="h3-title">SEO设置</h3>
clickScroll(val) {
this.activeName = val
let total = document.getElementById(val).offsetTop - 120
let distance = document.querySelector('.page-content').scrollTop
let step = total / 50;
const _this = this;
if (total > distance) {
smoothDown()
let newTotal = total -distance
step = newTotal / 50
} else {
let newTotal = distance - total
step = newTotal / 50
smoothUp()
}
function smoothDown () {
if (distance < total) {
distance += step
document.querySelector('.page-content').scrollTop = distance ;
setTimeout(smoothDown, 10);
} else {
document.querySelector('.page-content').scrollTop = total
}
}
function smoothUp () {
if (distance > total) {
distance -= step
document.querySelector('.page-content').scrollTop = distance
setTimeout(smoothUp, 10)
} else {
document.querySelector('.page-content').scrollTop = total
}
}
},
解决方案:
滚动页面的时候 让导航样式变化
- 在mouted – destroyed中 监听滚动
mounted() {
this.$nextTick(() => {
this.handleScroll()
})
window.addEventListener('scroll', this.handleScroll, true)
},
destroyed() {
window.addEventListener('scroll', this.handleScroll, false)
},
handleScroll() {
this.$nextTick(() => {
var anchor = document.querySelector('.anchor')
if (anchor) {
var top = document.querySelector('.page-content').scrollTop
if (top < 150) {
anchor.style.top = 230 - 8 - top + 'px'
} else {
anchor.style.top = '64px'
}
if (top < (document.getElementById('second').offsetTop-160)) {
this.activeName = 'first'
} else if (top < (document.getElementById('third').offsetTop-160)) {
this.activeName = 'second'
} else if (top < (document.getElementById('third').offsetTop-160) || top < document.getElementById('fourth').offsetTop-810) {
this.activeName = 'third'
} else if (top > document.getElementById('fourth').offsetTop-800) {
this.activeName = 'fourth'
}
}
})
},