feat: support multiple selectors for scrollOffset

pull/2104/head
Evan You 2 years ago
parent a6b18a8b9a
commit 86e2a6f972

@ -241,10 +241,20 @@ export function scrollTo(el: Element, hash: string, smooth = false) {
} }
if (target) { if (target) {
let offset = siteDataRef.value.scrollOffset const scrollOffset = siteDataRef.value.scrollOffset
if (typeof offset === 'string') { let offset: number = 0
offset = if (typeof scrollOffset === 'number') {
document.querySelector(offset)!.getBoundingClientRect().bottom + 24 offset = scrollOffset
} else if (typeof scrollOffset === 'string') {
offset = tryOffsetSelector(scrollOffset)
} else if (Array.isArray(scrollOffset)) {
for (const selector of scrollOffset) {
const res = tryOffsetSelector(selector)
if (res) {
offset = res
break
}
}
} }
const targetPadding = parseInt( const targetPadding = parseInt(
window.getComputedStyle(target).paddingTop, window.getComputedStyle(target).paddingTop,
@ -268,6 +278,14 @@ export function scrollTo(el: Element, hash: string, smooth = false) {
} }
} }
function tryOffsetSelector(selector: string): number {
const el = document.querySelector(selector)
if (!el) return 0
const bot = el.getBoundingClientRect().bottom
if (bot < 0) return 0
return bot + 24
}
function handleHMR(route: Route): void { function handleHMR(route: Route): void {
// update route.data on HMR updates of active page // update route.data on HMR updates of active page
if (import.meta.hot) { if (import.meta.hot) {

@ -67,8 +67,12 @@ export interface UserConfig<ThemeConfig = any>
/** /**
* Configure the scroll offset when the theme has a sticky header. * Configure the scroll offset when the theme has a sticky header.
* Can be a number or a selector element to get the offset from. * Can be a number or a selector element to get the offset from.
* Can also be an array of selectors in case some elements will be
* invisible due to responsive layout. VitePress will fallback to the next
* selector if a selector fails to match, or the matched element is not
* currently visible in viewport.
*/ */
scrollOffset?: number | string scrollOffset?: number | string | string[]
/** /**
* Enable MPA / zero-JS mode. * Enable MPA / zero-JS mode.

2
types/shared.d.ts vendored

@ -56,7 +56,7 @@ export interface SiteData<ThemeConfig = any> {
head: HeadConfig[] head: HeadConfig[]
appearance: boolean | 'dark' appearance: boolean | 'dark'
themeConfig: ThemeConfig themeConfig: ThemeConfig
scrollOffset: number | string scrollOffset: number | string | string[]
locales: LocaleConfig<ThemeConfig> locales: LocaleConfig<ThemeConfig>
localeIndex?: string localeIndex?: string
} }

Loading…
Cancel
Save