滚动消抖,回顶按钮加数字,其他微调

This commit is contained in:
tangly1024
2021-10-13 15:45:41 +08:00
parent 77f554bbc2
commit 4f8f5c3773
6 changed files with 68 additions and 54 deletions

View File

@@ -1,4 +1,4 @@
import React, { useEffect, useState } from 'react'
import React, { useCallback, useEffect, useState } from 'react'
import throttle from 'lodash.throttle'
import { useLocale } from '@/lib/locale'
@@ -8,29 +8,38 @@ import { useLocale } from '@/lib/locale'
* @returns {JSX.Element}
* @constructor
*/
const JumpToTop = () => {
const JumpToTop = ({ targetRef }) => {
const locale = useLocale()
const [show, switchShow] = useState(false)
const [percent, changePercent] = useState(0)
const scrollListener = useCallback(throttle(() => {
// 处理是否显示回到顶部按钮
const scrollY = window.pageYOffset
const fullHeight = targetRef.current.clientHeight - window.outerHeight
const shouldShow = scrollY > 100
if (shouldShow !== show) {
switchShow(shouldShow)
}
let per = parseFloat(((scrollY / fullHeight * 100)).toFixed(0))
if (per > 100) per = 100
changePercent(per)
}, 100))
useEffect(() => {
const scrollListener = throttle(() => {
// 处理是否显示回到顶部按钮
const shouldShow = window.scrollY > 100
if (shouldShow !== show) {
switchShow(shouldShow)
}
}, 500)
document.addEventListener('scroll', scrollListener)
return () => document.removeEventListener('scroll', scrollListener)
}, [show])
return (
<div
className={(show ? 'animate__fadeInUp' : 'animate__fadeOutUp') + ' animate__animated animate__faster'}>
className={(show ? 'animate__fade InUp' : 'animate__fadeOutUp') + ' animate__animated animate__faster'}>
<div
className='border dark:border-gray-500 dark:bg-gray-600 bg-white cursor-pointer hover:shadow-2xl'
onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })}>
<a className='dark:text-gray-200 fa fa-arrow-up p-4 transform hover:scale-150 duration-200' title={locale.POST.TOP}/>
<div className='absolute bg-white z-20 hover:opacity-0 w-11 py-2.5 text-center'>
{percent}%
</div>
<a className='dark:text-gray-200 fa fa-arrow-up p-4 transform hover:scale-150 duration-200'
title={locale.POST.TOP} />
</div>
</div>