@@ -11,16 +11,22 @@ function expandAllParents(navItem: HTMLElement) {
11
11
}
12
12
}
13
13
14
- function scrollCurrentNaviItemIntoView ( nav : HTMLElement , delay : number ) {
14
+ function scrollCurrentNaviItemIntoView ( nav : HTMLElement ) {
15
15
const currentNavItem = $ ( '.current' , nav ) ;
16
16
expandAllParents ( currentNavItem ) ;
17
- setTimeout ( ( ) => {
18
- if ( currentNavItem && ! isElementInViewport ( nav , currentNavItem ) ) {
19
- currentNavItem . scrollIntoView ( { behavior : 'smooth' , block : 'center' } ) ;
20
- window . scrollTo ( 0 , 0 ) ;
21
- }
22
- } , delay ) ;
17
+ if ( currentNavItem && ! isElementInViewport ( nav , currentNavItem ) ) {
18
+ const navRect = nav . getBoundingClientRect ( ) ;
19
+ const currentNavItemRect = currentNavItem . getBoundingClientRect ( ) ;
20
+ // Calculate the offset needed to scroll the current navigation item into view.
21
+ // The offset is determined by the difference between the top of the current navigation item and the top of the navigation container,
22
+ // adjusted by one-third of the height of the navigation container and half the height of the current navigation item.
23
+ const offset = currentNavItemRect . top - navRect . top - navRect . height / 3 + currentNavItemRect . height / 2 ;
24
+
25
+ // Scroll the navigation container by the calculated offset to bring the current navigation item into view.
26
+ nav . scrollTop = nav . scrollTop + offset ;
27
+ }
23
28
}
29
+
24
30
function isElementInViewport ( parent : HTMLElement , child : HTMLElement , ) : boolean {
25
31
const childRect = child . getBoundingClientRect ( ) ;
26
32
const parentRect = parent . getBoundingClientRect ( ) ;
@@ -41,8 +47,5 @@ export function initNav() {
41
47
navItems . forEach ( el => {
42
48
el . classList . add ( 'current' ) ;
43
49
} ) ;
44
- scrollCurrentNaviItemIntoView ( pagesNav , 100 ) ;
50
+ scrollCurrentNaviItemIntoView ( pagesNav ) ;
45
51
}
46
-
47
-
48
- // initNav();
0 commit comments