1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
| <script lang="ts"> import { defineComponent, onMounted, onUnmounted, reactive, toRefs } from "vue"; export default defineComponent({ props: { navList: { type: Array, default: [], }, anchorClass: { type: String, default: "", }, }, setup(props) { let DATA: any = reactive({ active: 0, }); let METHODS = reactive({ onScroll() { const navContents = document.querySelectorAll(props.anchorClass); const offsetTopArr: any[] = []; navContents.forEach((item) => { let newitem = <HTMLElement>item; offsetTopArr.push(newitem.offsetTop); }); const scrollTop = document.documentElement.scrollTop || document.body.scrollTop; let navIndex = 0; for (let n = 0; n < offsetTopArr.length; n++) { if (scrollTop >= offsetTopArr[n]) { navIndex = n; } } DATA.active = navIndex; }, scrollTo: (index: any) => { let navContents = document.querySelectorAll(props.anchorClass); const currentOffsetTop = <HTMLElement>navContents[index]; const targetOffsetTop = currentOffsetTop.offsetTop; let scrollTop = document.documentElement.scrollTop || document.body.scrollTop; const STEP = 50; if (scrollTop > targetOffsetTop) { smoothUp(); } else { smoothDown(); } function smoothDown() { if (scrollTop < targetOffsetTop) { if (targetOffsetTop - scrollTop >= STEP) { scrollTop += STEP; } else { scrollTop = targetOffsetTop; } document.body.scrollTop = scrollTop; document.documentElement.scrollTop = scrollTop; requestAnimationFrame(smoothDown); } } function smoothUp() { if (scrollTop > targetOffsetTop) { if (scrollTop - targetOffsetTop >= STEP) { scrollTop -= STEP; } else { scrollTop = targetOffsetTop; } document.body.scrollTop = scrollTop; document.documentElement.scrollTop = scrollTop; requestAnimationFrame(smoothUp); } } }, }); onMounted(() => { window.addEventListener("scroll", METHODS.onScroll); }); onUnmounted(() => { window.removeEventListener("scroll", METHODS.onScroll); }); return { ...toRefs(DATA), ...toRefs(METHODS), }; }, }); </script>
|