vue 使用scroll實現錨點
阿新 • • 發佈:2020-12-15
1.最近出來一個新需求,要求滾動分組時右邊出現導航欄,可以通過導航欄跳轉到相應分組,實現效果如下:
2.首先監聽滾動@scroll="scrollEvent"
,滾動方法實現如下:
// 監聽滾動
scrollEvent (e) {
this.showMao = true // 顯示導航欄
let scrollItems = document.querySelectorAll('.temp-items')
for (let i = scrollItems.length - 1; i >= 0; i--) {
let judge =
e.target.scrollTop >=
scrollItems[i].offsetTop - scrollItems[0].offsetTop - 80 // 減去80是我頁面佈局的原因,視情況而定
if (judge && this.toMove) { // 右邊導航欄跟隨滾動
this.toMove = true
this.activeStep = i
this.scrollLabel(`${i}child`)
break
}
}
},
3.實現導航跟隨頁面滾動方法
let _this = this
let t = 1
let queryId = document.getElementById(e)
queryId.scrollIntoView({behavior: 'smooth', block: 'center', inline: 'nearest'})
if (this.timer2) {
clearInterval(this.timer2)
}
// 未滾動後兩秒隱藏導航欄
this.timer2 = setInterval(() => {
if (t <= 0 && this.hideMao) {
clearInterval(_this.timer2)
_this.showMao = false
_this.$forceUpdate()
return
}
t--
}, 1000)
},
4.實現點選導航欄跳轉對應分組:
jump (e) {
this.toMove = false
let queryId = document.getElementById(e)
this.activeStep = e
new Promise(
function (resolve, reject) {
queryId.scrollIntoView(true)
},
).then(
(res) => {
this.toMove = true
},
)
},
5.頁面上也通過滑鼠移入移出改變導航欄顯示隱藏,如下;
<div class="page-container" @scroll="scrollEvent">
<div class="temp-items" :id="index" v-for="(option, index) in tempList" :key="'temp-'+index">
<div class="temp-top">
<div class="top-info">
<h3 class="top-title">{{option.name}}</h3>
<div class="top-text">{{option.desc || '暫無題組介紹'}}</div>
</div>
</div>
<div class="temp-fields" v-loading="loading">
<template-draggable ref="TemplateDraggable"
:templateValues="option.fields"
:templateId="''+index"
:readOnly="crfStatus===1 || proStatus ===0 || !anStatus"
:draggable="false"
:editorAble="false"
v-on:templateBack="templateEdit"
></template-draggable>
</div>
</div>
<transition name="fade">
<div class="maoDian" v-show="showMao" @mouseleave="showMao=false;hideMao=true" @mouseenter="hideMao=false">
<div v-for="(option, index) in tempList" :style="{color: activeStep === index ? '#1987e1' : '#5c5c5c'}"
:key="option.name">
<span :id="index+'child'" @click="jump(index)">{{option.name}}</span>
</div>
</div>
</transition>
</div>
6.不過在跳轉的時候我沒加平滑過渡,原因是加了平滑過渡後,還沒滾動完,Promise就執行完成了,toMove 狀態就改變了,導致後面滑動頁面,導航欄就不隨頁面滾動到相應目錄,效果如下:
希望路過的大佬救救孩子