这个锚点定位的思路非常简单,代码也非常简单,但是缺点就是不兼容IE9,暂时先以这个为思路分享下方法。
思路:
1.给dom元素设立锚点(这里以ID为锚点);
2.点击瞬间计算页面顶部到达dom的距离。
3.计算页面已经滚动的距离。
4.根据2和3判断需要上滚还是下滚。
5.滚动。
点击事件触发方法,jump的参数即为锚点ID:
源码:
<template>
<div style="height:600px;" class="step">
<el-button class="stepBtn" @click="jump('photo')" icon="el-icon-picture-outline-round" circle=""></el-button> -个人头像 <br>
<el-button class="stepBtn" @click="jump('user-info')" icon="el-icon-coordinate" circle=""></el-button> -个人信息 <br>
<el-button class="stepBtn" @click="jump('introduction')" icon="el-icon-edit-outline" circle=""></el-button> -个人介绍 <br>
<el-button class="stepBtn" @click="jump('job-intention')" icon="el-icon-suitcase" circle=""></el-button> -求职意向 <br>
<el-button class="stepBtn" @click="jump('educational-background')" icon="el-icon-office-building" circle=""></el-button> -教育经历 <br>
</div>
</template>
<script>
export default {
methods:{
jump(domId){
// 当前窗口正中心位置到指定dom位置的距离
//页面滚动了的距离
let height = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
//指定dom到页面顶端的距离
let dom = document.getElementById(domId);
let domHeight = dom.offsetTop+60;
//滚动距离计算
var S = Number(height) - Number(domHeight);
//判断上滚还是下滚
if(S<0){
//下滚
S = Math.abs(S);
window.scrollBy({ top: S, behavior: "smooth" });
}else if(S==0){
//不滚
window.scrollBy({ top: 0, behavior: "smooth" });
}else{
//上滚
S = -S
window.scrollBy({ top: S, behavior: "smooth" });
}
}
}
}
</script>
<style scoped>
.step{
font-family: "Helvetica Neue";
}
.stepBtn{
margin-bottom: 15px;
}
</style>