我正试图把两个按钮在一个垂直的长div的中心。这应该呈现箭头按钮的基础上的div在视口中可见的数量。请帮助。
所以我写了这个use Effect with scroll event listeners,它应该生成div的top样式作为状态(这里是[arrowPosition,setArrowPosition])。但是我的visibleHeight值不正确。当我从top滚动时,它工作正常,然后回到它应该停留的地方。div内部有惰性加载,所以div可能会扩展,所以我认为有必要为此使用逻辑。
useEffect(() => {
const handleScroll = () => {
const { top, bottom, height } = epgRowsSpanRef.current.getBoundingClientRect(),
windowHeight = window.innerHeight,
topIntersection = Math.max(0, top),
bottomIntersection = Math.max(0, windowHeight - bottom),
visibleHeight = Math.min(height, Math.max(0, windowHeight - topIntersection - bottomIntersection)),
visiblePercent = Math.round((visibleHeight / height) * 100);
setArrowPosition(`${visiblePercent / 2}%`);
console.log('show arrow', visibleHeight);
};
window.addEventListener('scroll', handleScroll);
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, [epgRowsSpanRef]);
1条答案
按热度按时间kxe2p93d1#
你应该使用intersection observer来完成这个任务。