评论区跳转逻辑优化

This commit is contained in:
tlyong1992
2022-05-31 15:03:15 +08:00
parent 516be7b937
commit 7b425891cc
2 changed files with 14 additions and 4 deletions

View File

@@ -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 (
<div id='comment' className='comment mt-5 text-gray-800 dark:text-gray-300'>
<Tabs>

View File

@@ -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 () => {