<tr class="step-jump"></tr>
<tr class="step-jump"></tr>
<div style="position:fixed;top:25%;right:0;">
<el-steps
direction="vertical"
finish-status="wait"
space="50px"
:active="activeStep">
<el-step
v-for="(item, index) in stepsArr"
:key="index"
:title="item.title"
@click.native="jump(index)">
</el-step>
</el-steps>
</div>
js:
data() {
return {
activeStep: 0,
scrollTop: 0, // 没用到
stepsArr: [
{ title: '一般状况' },
{ title: '生活方式' },
{ title: '脏器功能' },
{ title: '查体' },
{ title: '辅助检查' },
{ title: '现存主要健康问题' },
{ title: '住院治疗情况' },
{ title: '主要用药情况' },
{ title: '非免疫规划预防接种史' },
{ title: '健康评价' },
{ title: '健康指导' }
]
}
},
mounted() {
this.$nextTick(function() {
window.addEventListener('scroll', this.onScroll)
})
},
methods:{
// 当元素滚动条被滚动时运行的脚本
onScroll() {
// var box = document.getElementById('box')
// var t = document.documentElement.scrollTop || document.body.scrollTop
// box.style.top = t + 'px'
var jump = document.querySelectorAll('.step-jump')
var distance =
document.documentElement.scrollTop ||
window.pageYOffset ||
document.body.scrollTop
jump.forEach((item, index) => {
if (distance >= item.offsetTop) {
this.activeStep = index
}
})
},
// 锚点点击
jump(index) {
console.log(index)
this.activeStep = index
// 用 class=".step-jump" 添加锚点,此时的类名要放在tr上,放在td上不对,
// 以后做的时候要注意这点,不是表格的时候,如何放置锚点
let jump = document.querySelectorAll('.step-jump')
// 通过 offsetTop 获取对象到窗体顶部的距离,然后赋值给 scrollTop,就能实现锚点的功能
let total = jump[index].offsetTop
console.log(total)
// scrollTop滚动条距离页面的距离
let distance =
document.documentElement.scrollTop ||
window.pageYOffset ||
document.body.scrollTop
// console.log(distance)
// 平滑滚动,时长500ms,每10ms一跳,共50跳
let step = total / 50
if (total > distance) {
smoothDown()
} else {
let newTotal = distance - total
step = newTotal / 50
smoothUp()
}
function smoothDown() {
if (distance < total) {
distance += step
document.body.scrollTop = distance
document.documentElement.scrollTop = distance
window.pageYOffset = distance
setTimeout(smoothDown, 10)
} else {
document.body.scrollTop = total
document.documentElement.scrollTop = total
window.pageYOffset = total
}
}
function smoothUp() {
if (distance > total) {
distance -= step
document.body.scrollTop = distance
document.documentElement.scrollTop = distance
window.pageYOffset = distance
setTimeout(smoothUp, 10)
} else {
document.body.scrollTop = total
document.documentElement.scrollTop = total
window.pageYOffset = total
}
}
}
}