feat: scrollOffset option

pull/501/head
Evan You 3 years ago
parent 70cfffb9db
commit b66785d68a

@ -2,6 +2,7 @@ import { reactive, inject, markRaw, nextTick, readonly } from 'vue'
import type { Component, InjectionKey } from 'vue' import type { Component, InjectionKey } from 'vue'
import { PageData } from '../shared' import { PageData } from '../shared'
import { inBrowser } from './utils' import { inBrowser } from './utils'
import { siteDataRef } from './data'
export interface Route { export interface Route {
path: string path: string
@ -192,7 +193,20 @@ function scrollTo(el: HTMLElement, hash: string, smooth = false) {
} }
if (target) { if (target) {
const targetTop = (target as HTMLElement).offsetTop let offset = siteDataRef.value.scrollOffset
if (typeof offset === 'string') {
offset =
document.querySelector(offset)!.getBoundingClientRect().bottom + 24
}
const targetPadding = parseInt(
window.getComputedStyle(target as HTMLElement).paddingTop,
10
)
const targetTop =
window.scrollY +
(target as HTMLElement).getBoundingClientRect().top -
offset +
targetPadding
// only smooth scroll if distance is smaller than screen height. // only smooth scroll if distance is smaller than screen height.
if (!smooth || Math.abs(targetTop - window.scrollY) > window.innerHeight) { if (!smooth || Math.abs(targetTop - window.scrollY) > window.innerHeight) {
window.scrollTo(0, targetTop) window.scrollTo(0, targetTop)

@ -51,6 +51,12 @@ export interface UserConfig<ThemeConfig = any> {
outDir?: string outDir?: string
shouldPreload?: (link: string, page: string) => boolean shouldPreload?: (link: string, page: string) => boolean
/**
* Configure the scroll offset when the theme has a sticky header.
* Can be a number or a selector element to get the offset from.
*/
scrollOffset?: number | string
/** /**
* Enable MPA / zero-JS mode * Enable MPA / zero-JS mode
* @experimental * @experimental
@ -243,6 +249,7 @@ export async function resolveSiteData(
head: userConfig.head || [], head: userConfig.head || [],
themeConfig: userConfig.themeConfig || {}, themeConfig: userConfig.themeConfig || {},
locales: userConfig.locales || {}, locales: userConfig.locales || {},
langs: createLangDictionary(userConfig) langs: createLangDictionary(userConfig),
scrollOffset: userConfig.scrollOffset || 90
} }
} }

1
types/shared.d.ts vendored

@ -22,6 +22,7 @@ export interface SiteData<ThemeConfig = any> {
description: string description: string
head: HeadConfig[] head: HeadConfig[]
themeConfig: ThemeConfig themeConfig: ThemeConfig
scrollOffset: number | string
locales: Record<string, LocaleConfig> locales: Record<string, LocaleConfig>
/** /**
* Available locales for the site when it has defined `locales` in its * Available locales for the site when it has defined `locales` in its

Loading…
Cancel
Save