vue實現(xiàn)錨點跳轉(zhuǎn)及滾動監(jiān)聽的方法
vue中實現(xiàn)錨點跳轉(zhuǎn)以及滾動監(jiān)聽跳轉(zhuǎn)到相應(yīng)標簽的方法,供大家參考,具體內(nèi)容如下
*注意·如果scroll-item的最后一個元素高度必須大于等于滾動區(qū)域的高度,不然最后一個元素就滾動不上去,
實際效果圖

代碼結(jié)構(gòu)
// Html結(jié)構(gòu)
<template>
? <div>
? ? <div class="list">
? ? ? <ul>
? ? ? ? <li v-for="(item,index) in title_list" :key="index">
? ? ? ? <span ref="spans" :style="{color: activeStep === index ? '#1987e1' : '#000000'}"
? ? ? ? @click="jump(index)">
? ? ? ? {{item.title}}
? ? ? ? </span>
? ? ? ? </li>
? ? ? </ul>
? ? </div>
? ? <div class="result" @scroll="onScroll" >
? ? ? <div class="scroll-item"><span>第一</span></div>
? ? ? <div class="scroll-item"><span>第二</span></div>
? ? ? <div class="scroll-item"><span>第三</span></div>
? ? ? <div class="scroll-item"><span>第四</span></div>
? ? </div>
? </div>
</template>//功能實現(xiàn)代碼
<script>
export default {
? methods:{
? ? jump(index) {
? ? ? var items = document.querySelectorAll(".scroll-item");
? ? ? for (var i = 0; i < items.length; i++) {
? ? ? ? if (index === i) {
? ? ? ? ? items[i].scrollIntoView({
? ? ? ? ? ? block: "start",//默認跳轉(zhuǎn)到頂部
? ? ? ? ? ? behavior: "smooth"http://滾動的速度
? ? ? ? ? });
? ? ? ? }
? ? ? }
? ? },
? ? onScroll(e) {
? ? ? let scrollItems = document.querySelectorAll(".scroll-item");
? ? ? for (let i = scrollItems.length - 1; i >= 0; i--) {
? ? ? ? // 判斷滾動條滾動距離是否大于當前滾動項可滾動距離
? ? ? ? let judge =
? ? ? ? ? e.target.scrollTop >=
? ? ? ? ? scrollItems[i].offsetTop - scrollItems[0].offsetTop;
? ? ? ? if (judge) {
? ? ? ? ? this.activeStep = i;
? ? ? ? ? break;
? ? ? ? }
? ? ? }
? ? }, ? ?
? },
? data() {
? ? return {
? ? ? activeStep :0,
? ? ? title_list:[
? ? ? ? {title:'第一'},
? ? ? ? {title:'第二'}, ? ? ? ?
? ? ? ? {title:'第三'},
? ? ? ? {title:'第四'},
? ? ? ? ]
? ? }
? }
}
</script>//樣式
<style>
.list {
? width: 100%;
? height: 40px;
? margin-bottom: 20px;
? background: pink;
}
ul {
? width: 100%;
? height: 40px;
? line-height: 40px;
? list-style: none;
}
li {
? float: left;
? width: 20%;
? font-size: 30px;
}
li>span {
? cursor:pointer;
}
.result {
? width: 100%;
? height: 500px;
? overflow: scroll;
}
.scroll-item {
? width: 100%;
? height: 500px;
? margin-top:20px;
? background: yellow;
}
.scroll-item>span {
? font-size: 40px;
}
.scroll-item:first-child {
? margin-top: 0;
}
.scroll-item:last-child {
? height: 500px;
}/ * 最后一個元素的最小高度要大于等于父元素的高度,如果scroll-item為高度自適應(yīng)的話,那么最后一個scroll-item就得設(shè)置min-height:100%* /
</style>以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
element-ui中表格設(shè)置正確的排序及設(shè)置默認排序
表格中有時候會有排序的需求,下面這篇文章主要給大家介紹了關(guān)于element-ui中表格設(shè)置正確的排序及設(shè)置默認排序的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2023-05-05
vue+element-ui集成隨機驗證碼+用戶名+密碼的form表單驗證功能
在登入頁面,我們往往需要通過輸入驗證碼才能進行登入,那我們下面就詳講一下在vue項目中如何配合element-ui實現(xiàn)這個功能,需要的朋友可以參考下2018-08-08
vue2使用element-ui,el-table不顯示,用npm安裝方式
這篇文章主要介紹了vue2使用element-ui,el-table不顯示,用npm安裝方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07

