diff --git a/docs/examples/scrollIntoView.tsx b/docs/examples/scrollIntoView.tsx index 5b73764..77a7892 100644 --- a/docs/examples/scrollIntoView.tsx +++ b/docs/examples/scrollIntoView.tsx @@ -32,7 +32,7 @@ const App = () => { > Create -
+
@@ -65,7 +65,7 @@ const App = () => { ), target: () => updateBtnRef.current, scrollIntoViewOptions: { - block: 'start' + block: 'start', behavior:'smooth' } }, { diff --git a/src/hooks/useTarget.ts b/src/hooks/useTarget.ts index 432c3b2..cf2205c 100644 --- a/src/hooks/useTarget.ts +++ b/src/hooks/useTarget.ts @@ -44,8 +44,8 @@ export default function useTarget( // Exist target element. We should scroll and get target position if (!isInViewPort(targetElement) && open) { targetElement.scrollIntoView(scrollIntoViewOptions); + return; } - const { left, top, width, height } = targetElement.getBoundingClientRect(); const nextPosInfo: PosInfo = { left, top, width, height, radius: 0 }; @@ -65,12 +65,23 @@ export default function useTarget( const getGapOffset = (index: number) => (Array.isArray(gap?.offset) ? gap?.offset[index] : gap?.offset) ?? 6; + const scrollEndUpdatePos = ()=>{ + if(window.requestAnimationFrame){ + window.requestAnimationFrame(updatePos); + return; + } + setTimeout(updatePos,1000/60); + } + useLayoutEffect(() => { updatePos(); // update when window resize window.addEventListener('resize', updatePos); + // update when window scroll end + window.addEventListener('scrollend',scrollEndUpdatePos); return () => { window.removeEventListener('resize', updatePos); + window.removeEventListener('scrollend',scrollEndUpdatePos); }; }, [targetElement, open, updatePos]);