import { useGlobal } from '@/lib/global' import { useEffect, useState } from 'react' import Typed from 'typed.js' import CONFIG_HEXO from '../config_hexo' let wrapperTop = 0 let windowTop = 0 let autoScroll = false /** * * @returns 头图 */ const Header = props => { const [typed, changeType] = useState() const { isDarkMode } = useGlobal() const { siteInfo } = props useEffect(() => { scrollTrigger() updateHeaderHeight() updateTopNav() if (!typed && window && document.getElementById('typed')) { changeType( new Typed('#typed', { strings: CONFIG_HEXO.HOME_BANNER_GREETINGS, typeSpeed: 200, backSpeed: 100, backDelay: 400, showCursor: true, smartBackspace: true }) ) } window.addEventListener('scroll', scrollTrigger) window.addEventListener('resize', updateHeaderHeight) return () => { window.removeEventListener('scroll', scrollTrigger) window.removeEventListener('resize', updateHeaderHeight) } }) const autoScrollEnd = () => { if (autoScroll) { windowTop = window.scrollY autoScroll = false } } const scrollTrigger = () => { const scrollS = window.scrollY const nav = document.querySelector('#sticky-nav') if (scrollS < 500) { nav && nav.classList.replace('bg-white', 'bg-none') nav && nav.classList.replace('text-black', 'text-white') } else { nav && nav.classList.replace('bg-none', 'bg-white') nav && nav.classList.replace('text-white', 'text-black') } // 自动滚动 if ((scrollS > windowTop) & (scrollS < window.innerHeight) && !autoScroll ) { autoScroll = true window.scrollTo({ top: wrapperTop, behavior: 'smooth' }) setTimeout(autoScrollEnd, 500) } if ((scrollS < windowTop) && (scrollS < window.innerHeight) && !autoScroll) { autoScroll = true window.scrollTo({ top: 0, behavior: 'smooth' }) setTimeout(autoScrollEnd, 500) } windowTop = scrollS updateTopNav() } const updateTopNav = () => { if (!isDarkMode) { const stickyNavElement = document.getElementById('sticky-nav') if (window.scrollY < window.innerHeight) { stickyNavElement?.classList?.add('dark') } else { stickyNavElement?.classList?.remove('dark') } } } function updateHeaderHeight () { setTimeout(() => { if (window) { const wrapperElement = document.getElementById('wrapper') wrapperTop = wrapperElement?.offsetTop } }, 500) } return ( ) } export default Header