feat: improve hash target positioning upon initial navigation

This commit is contained in:
Justineo 2021-10-21 18:38:51 +08:00
parent 2bfe8ad8ec
commit 047867d72a
No known key found for this signature in database
GPG Key ID: B73F0979CF18A0EA
3 changed files with 24 additions and 1 deletions

View File

@ -4,6 +4,22 @@ function timeout (t) {
}) })
} }
let paddingTopInPixels = null
function getScrollPaddingTopInPixels () {
if (paddingTopInPixels !== null) {
return paddingTopInPixels
}
const measurer = document.createElement('div')
const paddingTop = getComputedStyle(document.documentElement).scrollPaddingTop
measurer.style.position = 'absolute'
measurer.style.visibility = 'hidden'
measurer.style.height = paddingTop
document.body.appendChild(measurer)
paddingTopInPixels = measurer.offsetHeight
measurer.remove()
return paddingTopInPixels
}
export default async function scrollBehavior (to) { export default async function scrollBehavior (to) {
if (to.hash) { if (to.hash) {
// scroll to anchor by returning the selector // scroll to anchor by returning the selector
@ -11,7 +27,7 @@ export default async function scrollBehavior (to) {
return { return {
selector: decodeURIComponent(to.hash), selector: decodeURIComponent(to.hash),
offset: { offset: {
y: 120 y: getScrollPaddingTopInPixels()
} }
} }
} }

View File

@ -19,6 +19,7 @@ html
font-weight 400 font-weight 400
color #333 color #333
scroll-behavior smooth scroll-behavior smooth
scroll-padding-top 120px
html html
body body
@ -39,3 +40,6 @@ a:focus
main main
line-height 1.5 line-height 1.5
.DocSearch-Container
backdrop-filter blur(4px)

View File

@ -21,6 +21,9 @@ export default ({ app, route }) => {
setTimeout(() => { setTimeout(() => {
const selector = decodeURIComponent(to.hash) const selector = decodeURIComponent(to.hash)
const anchor = document.querySelector(selector) const anchor = document.querySelector(selector)
if (!anchor) {
return
}
if (anchor.tagName === 'CODE') { if (anchor.tagName === 'CODE') {
target = anchor.closest('tr') target = anchor.closest('tr')