dom.getBoundingClientRect() 用来获取元素相关信息,比如,元素自身大小、元素位置等
// top 元素相对于页面顶部的距离
// height 元素自身高度
const { top, height } = dom.getBoundingClientRect();
步骤:
- 创建两个 ref 对象:1 可滚动区域 DOM 2 导航栏作者信息 DOM
- 创建控制导航栏作者信息是否显示的状态
- 导入 lodash 的节流函数 throttle
- 监听页面滚动,判断是否展示导航栏作者信息,来修改状态
核心代码:
article/index.tsx 中:
import throttle from 'lodash/throttle'
const Article = () => {
const wrapperRef = useRef<HTMLDivElement>(null)
const authorRef = useRef<HTMLDivElement>(null)
const [showNavAuthor, setShowNavAuthor] = useState(false)
// 导航栏中展示作者信息
useEffect(() => {
if (loading) return
const wrapperDOM = wrapperRef.current!
// 创建一个节流函数
const handleScroll = throttle(() => {
const { bottom } = authorRef.current!.getBoundingClientRect()
// 44 是 NavBar 的高度,因为 NavBar 会挡住页面内容,所以,此处需要减去它的高度
if (bottom - 44 <= 0) {
setShowNavAuthor(true)
} else {
setShowNavAuthor(false)
}
}, 200)
wrapperDOM.addEventListener('scroll', handleScroll)
return () => wrapperDOM.removeEventListener('scroll', handleScroll)
}, [loading])
const renderArticle = () => {
return (
<div className="wrapper" ref={wrapperRef}>
// ...
<div className="author" ref={authorRef}>
</div>
</div>
)
}
// ...
return (
// ...
<NavBar>
{showNavAuthor && (
<div className="nav-author">...</div>
}
</NavBar>
)
}