From 8d8cd8f76155cc4b6b88468d7e3a6d8cb1c9e330 Mon Sep 17 00:00:00 2001 From: chenxi-20 <2465950588@qq.com> Date: Sat, 25 Mar 2023 16:12:37 +0800 Subject: [PATCH] =?UTF-8?q?fix(anchor):=20=E4=BF=AE=E5=A4=8D=E5=B5=8C?= =?UTF-8?q?=E5=A5=97=E9=94=9A=E7=82=B9=E6=97=A0=E6=B3=95=E6=8C=87=E7=A4=BA?= =?UTF-8?q?=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/anchor/index.js | 28 ++++++++++++++++++---------- src/anchor/vue.js | 1 + 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/src/anchor/index.js b/src/anchor/index.js index b1c711f..4534f83 100644 --- a/src/anchor/index.js +++ b/src/anchor/index.js @@ -78,15 +78,15 @@ const getCurrentAnchor = ({ vm, state, link, emit }) => { const addObserver = ({ props, state }) => { const { links } = props - const { intersectionObserver } = state + const { intersectionObserver, expandLink } = state const observer = (list) => { list.forEach(item => { const link = item.link + expandLink[link] = item + const linkEl = document.querySelector(link) + linkEl && intersectionObserver.observe(linkEl) if (item.children) { observer(item.children) - } else { - const linkEl = document.querySelector(link) - linkEl && intersectionObserver.observe(linkEl) } }) } @@ -123,18 +123,26 @@ export const unmounted = ({ state }) => () => { } export const onItersectionObserver = ({ vm, state, props, emit }) => () => { - + const { expandLink, scrollContainer } = state + const containerTop = scrollContainer.getBoundingClientRect().top + 10 state.intersectionObserver = new IntersectionObserver((entries) => { entries.forEach(item => { const key = item.target.id state.observerLinks[key] = item }) - for (let item of Object.values(state.observerLinks)) { - if (item.isIntersecting && item.intersectionRatio > 0) { - const link = `#${item.target.id}` - getCurrentAnchor({ vm, state, link, emit }) - break + for (let key in state.observerLinks) { + if (Object.prototype.hasOwnProperty.call(state.observerLinks, key)) { + const item = state.observerLinks[key] + if (item.isIntersecting && item.intersectionRatio >= 0 && item.target.getBoundingClientRect().top < containerTop) { + const link = `#${item.target.id}` + if (!expandLink[link].children) { + getCurrentAnchor({ vm, state, link, emit }) + break + } else { + getCurrentAnchor({ vm, state, link, emit }) + } + } } } }) diff --git a/src/anchor/vue.js b/src/anchor/vue.js index 60a473f..bae3274 100644 --- a/src/anchor/vue.js +++ b/src/anchor/vue.js @@ -19,6 +19,7 @@ export const renderless = (props, { onMounted, onUnmounted, onUpdated, reactive const state = reactive({ currentLink: '', observerLinks: {}, + expandLink: {}, intersectionObserver: null, scrollContainer: null, currentHash: ''