vue+element 学习之路(十三)scrollBy简单实现锚点定位(单向)

在这里插入图片描述
这个锚点定位的思路非常简单,代码也非常简单,但是缺点就是不兼容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>

  • 10
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值