diff --git a/components/Header.js b/components/Header.js index 2d29c1a4..ac0849ea 100644 --- a/components/Header.js +++ b/components/Header.js @@ -2,8 +2,7 @@ import BLOG from '@/blog.config' import { useGlobal } from '@/lib/global' import { faAngleDown } from '@fortawesome/free-solid-svg-icons' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' -import throttle from 'lodash.throttle' -import { useCallback, useEffect, useState } from 'react' +import { useEffect, useState } from 'react' import Typed from 'typed.js' /** @@ -32,32 +31,38 @@ export default function Header () { let autoScroll = false const autoScrollEnd = () => { - windowTop = window.scrollY - autoScroll = false + if (autoScroll) { + console.log('结束自动滚动') + windowTop = window.scrollY + autoScroll = false + } } - const scrollTrigger = throttle(() => { - console.log('触发 scrollTrigger') + const scrollTrigger = () => { if ( (window.scrollY > windowTop) & (window.scrollY < window.innerHeight) & !autoScroll ) { + console.log('自动滚下', window.scrollY, windowTop) autoScroll = true - scrollTo(wrapperTop, autoScrollEnd) + window.scrollTo({ top: wrapperTop, behavior: 'smooth' }) + setTimeout(autoScrollEnd, 500) } if ( (window.scrollY < windowTop) & (window.scrollY < window.innerHeight) & !autoScroll ) { + console.log('自动滚上') autoScroll = true - scrollTo(0, autoScrollEnd) + window.scrollTo({ top: 0, behavior: 'smooth' }) + setTimeout(autoScrollEnd, 500) } windowTop = window.scrollY updateTopNav() - }, 500) + } const updateTopNav = () => { if (theme !== 'dark') { @@ -92,19 +97,19 @@ export default function Header () { return ( ) } - -/** - * Native scrollTo with callback - * @param offset - offset to scroll to - * @param callback - callback function - */ -const scrollTo = throttle((offset, callback) => { - const fixedOffset = offset.toFixed() - const onScroll = function () { - console.log('触发 scrollTo') - if (window.pageYOffset.toFixed() === fixedOffset) { - window.removeEventListener('scroll', onScroll) - window.onscroll = function () {} - callback() - } - } - - window.addEventListener('scroll', onScroll) - window.onscroll = onScroll() - window.scrollTo({ - top: offset, - behavior: 'smooth' - }) -}, 500)