Files
NotionNext/components/Progress.js
2021-09-29 12:52:24 +08:00

36 lines
1.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import React, { useEffect, useState } from 'react'
import throttle from 'lodash.throttle'
/**
* 跳转到网页顶部当屏幕下滑500像素后会出现该控件
* @returns {JSX.Element}
* @constructor
*/
const Progress = ({ targetRef }) => {
const [percent, changePercent] = useState(0)
useEffect(() => {
const scrollListener = throttle(() => {
if (targetRef.current) {
const fullHeight = targetRef.current.clientHeight
const per = parseFloat(((window.scrollY / (fullHeight - 100) * 100)).toFixed(0))
changePercent(per)
}
// console.log('滚动信息', window.scrollY, fullHeight, per)
}, 1)
document.addEventListener('scroll', scrollListener)
return () => document.removeEventListener('scroll', scrollListener)
}, [percent])
return (
<>
{/* 顶部进度条 */}
<div className='h-1.5 fixed top-0 w-full shadow-2xl z-40'>
<div className='h-1 bg-blue-500 fixed top-0 w-1 duration-200' style={{ width: `${percent}%` }}/>
{/* <div className='debug'>{percent}</div> */}
</div>
</>
)
}
export default Progress