背景
前不久有個需求,上半部分是el-step步驟條,下半部分是一些文字說明,需要實現點擊步驟條中某個步驟自定義定位到對應部分的文字說明,同時滾動內容區域的時候還要自動選中對應區域的步驟。element-ui-plus的有錨點這個組件,但是他的觸發內容是三個div,我的是一個組件,所以當時就沒用這個,直接就重寫了。
實現:
在el-step上添加click事件
// 使用scroll來滾動到對應的內容區域
const scroll = (stepNumber: number) => {// contentRef為對應的內容區域上的refconst targetElement = contentRef.value[stepNumber];if (targetElement) {nextTick(() => {targetElement.scrollIntoView({behavior: 'smooth',block: 'start',});});}
};
使用html5的API - IntersectionObserver來實現監聽滾動區域,然后給對應區域的step賦值。
在onmounted中調用方法去new?IntersectionObserver();
onMounted(() => {initObserver();
});// 監聽滾動
const initObserver = () => {const observer = new IntersectionObserver((entries) => {entries.forEach((entry) => {if (entry.isIntersecting) {const index = contentRef.value.findIndex((el: any) => el === entry.target,);// activeStep就是el-steps上綁定的:activeif (index !== -1) {activeStep.value = index;}}});},// rootRef就是對應滾動內容的父容器的ref{root: rootRef.value, // 監聽tip里的視口threshold: 0.9, // 90%進入視圖時才觸發},);contentRef.value.forEach((el: any) => observer.observe(el));
};
html結構
<div><el-steps :active="activeStep"><el-stepv-for="(item, index) in steps":key="index":title="item.title"@click.native="scroll(index)"></el-step></el-steps></div><div ref="rootRef"><divv-for="(img, index) in imgs":key="index"class="imgContainer"ref="contentRef"><img :src="img.src"/></div></div>