From 7b425891cc1921b6875537c92ee7549aad3d772d Mon Sep 17 00:00:00 2001 From: tlyong1992 Date: Tue, 31 May 2022 15:03:15 +0800 Subject: [PATCH] =?UTF-8?q?=E8=AF=84=E8=AE=BA=E5=8C=BA=E8=B7=B3=E8=BD=AC?= =?UTF-8?q?=E9=80=BB=E8=BE=91=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- components/Comment.js | 11 +++++++++++ components/WalineComponent.js | 7 +++---- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/components/Comment.js b/components/Comment.js index 4bae2665..20e1b119 100644 --- a/components/Comment.js +++ b/components/Comment.js @@ -2,6 +2,7 @@ import BLOG from '@/blog.config' import dynamic from 'next/dynamic' import Tabs from '@/components/Tabs' import { useGlobal } from '@/lib/global' +import React from 'react' const WalineComponent = dynamic( () => { @@ -46,6 +47,16 @@ const Comment = ({ frontMatter }) => { } const { isDarkMode } = useGlobal() + // 需要跳转到评论区域 + React.useEffect(() => { + setTimeout(() => { + if (window.location.hash) { + const commentNode = document.getElementById('comment') + commentNode.scrollIntoView({ block: 'start', behavior: 'smooth' }) + } + }, 200) + }, []) + return (
diff --git a/components/WalineComponent.js b/components/WalineComponent.js index 9fea1463..99596762 100644 --- a/components/WalineComponent.js +++ b/components/WalineComponent.js @@ -26,12 +26,9 @@ const WalineComponent = (props) => { router.events.on('routeChangeComplete', updateWaline) const anchor = window.location.hash - /** 需要跳转到评论区 */ if (anchor) { // 选择需要观察变动的节点 const targetNode = document.getElementsByClassName('wl-cards')[0] - const commentNode = document.getElementById('comment') - commentNode.scrollIntoView({ block: 'start', behavior: 'smooth' }) // 当观察到变动时执行的回调函数 const mutationCallback = (mutations) => { @@ -44,6 +41,7 @@ const WalineComponent = (props) => { setTimeout(() => { anchorElement.classList.add('animate__animated') anchorElement.classList.add('animate__bounceIn') + observer.disconnect() }, 300) } } @@ -51,7 +49,8 @@ const WalineComponent = (props) => { } // 观察子节点 变化 - new MutationObserver(mutationCallback).observe(targetNode, { childList: true }) + const observer = new MutationObserver(mutationCallback) + observer.observe(targetNode, { childList: true }) } return () => {