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) {
let offset = siteDataRef.value.scrollOffset
if (typeof offset === 'string') {
offset =
document.querySelector(offset)!.getBoundingClientRect().bottom + 24
const scrollOffset = siteDataRef.value.scrollOffset
let offset: number = 0
if (typeof scrollOffset === 'number') {
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(
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 {
// update route.data on HMR updates of active page
if (import.meta.hot) {

@ -67,8 +67,12 @@ export interface UserConfig<ThemeConfig = any>
/**
* 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 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.

2
types/shared.d.ts vendored

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

Loading…
Cancel
Save