vue实现锚点定位功能

一、监听滚动条(使用@scroll却没效果是吧)

参考链接:VUE@Scroll无效问题原因分析

1.1 html代码
<!--重点是要加样式-->
<template>
  <div class="body-container" @scroll="scrollEvent">
  	.......
  </div>
<template>
1.2 css样式
.body-container{
    position: fixed;
    top:0rem;
    left: 0;
    right:0;
    bottom: 0;
    overflow: auto
}
1.3 方法
scrollEvent(e){
	console.log(e.srcElement.scrollTop)//滚动条变化
}

二 、结合案例

1.1 代码
<!--内容部分(重点:添加class样式)-->
<div v-for="(item,index) in contents" :key="index" v-html="item" class="d_jump"></div>
<!--目录部分(重点:添加click事件)-->
<ul>
	<li v-for="(itemy,index) in articleName" :key="index"  :class="{active:catalogCur==index}" @click="jump(index)">{{itemy}}</li>
</ul> 
1.2 VUE数据
export default {
    data () {   
        return {
            catalogCur:0
        }
    }
}
1.3 方法

参考链接:VUE锚点定位scrollIntoView

/*监听滚动(结合前面的@scroll) */
scrollEvent(e){
	let scrollItems = document.querySelectorAll('.d_jump')
	for (let i = scrollItems.length - 1; i >= 0; i--) {
        // 判断滚动条滚动距离是否大于当前滚动项可滚动距离
        let judge = e.target.scrollTop >= scrollItems[i].offsetTop - scrollItems[0].offsetTop
        if (judge) {
            this.catalogCur = i
            break
        }
    }

	//滚动条触底了
	if(e.srcElement.scrollTop+e.srcElement.offsetHeight==e.srcElement.scrollHeight){
		this.catalogCur = this.articleName.length-1
	}
        
    //console.log(e.srcElement.scrollTop)//滚动条高度
    //console.log(e.srcElement.offsetHeight)//屏幕高度
    //console.log(e.srcElement.scrollHeight)//内容高度
    //'下拉获取更多'的功能(还有10像素就触发):滚动的像素+容器的高度>可滚动的总高度-10像素
}

/*目录点击定位效果:有兼容问题,借鉴了很多其他方法却一直不成功,无奈之后使用了scrollIntoView*/
jump (index) {
    this.catalogCur=index;
    let jump = document.querySelectorAll('.d_jump')
    jump[index].scrollIntoView({block: "start", behavior: "smooth"});
}
1.4 样式 (非关注的点,样式不全)
li{
    position: relative;
    height: 45px;
    line-height: 45px;
    padding-left: 15px;
}

li.active{
    color: #2f9fca;
}
li.active{
    color: #2f9fca;
}

li.active::before{
    content: " ";
    position: absolute;
    height: 20px;
    width: 2px;
    background-color: #2f9fca;
    left: 0;
    top:13px;
}

li.active::before{
    content: " ";
    position: absolute;
    height: 20px;
    width: 2px;
    background-color: #2f9fca;
    left: 0;
    top:13px;
}
  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值