@@ -51,9 +51,17 @@ const getRelativeDistance = (
5151 console . warn ( 'Please pass correct selector string for scrollTo()!' ) ;
5252 return 0 ;
5353 }
54- const dis =
55- elm . getBoundingClientRect ( ) [ attrMap . leftTop ] -
56- parent . getBoundingClientRect ( ) [ attrMap . leftTop ] ;
54+ let dis = 0 ;
55+
56+ // if parent is document.documentElement or document.body
57+ if ( ! parent . parentElement || ! parent . parentElement . parentElement ) {
58+ dis = elm . getBoundingClientRect ( ) [ attrMap . leftTop ] ;
59+ } else {
60+ dis =
61+ elm . getBoundingClientRect ( ) [ attrMap . leftTop ] -
62+ parent . getBoundingClientRect ( ) [ attrMap . leftTop ] ;
63+ }
64+
5765 return dis ;
5866 }
5967 return 0 ;
@@ -111,7 +119,7 @@ export const useSmoothScroll = ({
111119 isBottomEdge ( ) ? setReachBottom ( true ) : setReachBottom ( false ) ;
112120 } ) ;
113121
114- const scrollTo = ( target ?: number | string ) => {
122+ const scrollTo = ( target ?: number | string , offset ?: number ) => {
115123 if ( ! ref || ! ref . current ) {
116124 console . warn (
117125 'Please pass `ref` property for your scroll container! \n Get more info at https://github.com/ron0115/react-smooth-scroll-hook'
@@ -125,8 +133,15 @@ export const useSmoothScroll = ({
125133 'Please pass a valid property for `scrollTo()`! \n Get more info at https://github.com/ron0115/react-smooth-scroll-hook'
126134 ) ;
127135 }
136+
128137 const initScrollLeftTop = elm [ attrMap . scrollLeftTop ] ;
129- const distance = getRelativeDistance ( target , elm , attrMap ) ;
138+
139+ let distance = getRelativeDistance ( target , elm , attrMap ) ;
140+ console . log ( distance ) ;
141+ // set a offset
142+ if ( typeof offset === 'number' ) {
143+ distance += offset ;
144+ }
130145
131146 let _speed = speed ;
132147 const cb = ( ) => {
0 commit comments