docs_vue2/app/router.scrollBehavior.js

40 lines
924 B
JavaScript
Raw Permalink Normal View History

2021-10-20 10:24:04 +08:00
function timeout (t) {
return new Promise(resolve => {
setTimeout(resolve, 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
}
2021-10-20 10:24:04 +08:00
export default async function scrollBehavior (to) {
2021-10-18 18:52:29 +08:00
if (to.hash) {
2020-08-13 11:47:56 +08:00
// scroll to anchor by returning the selector
2021-10-20 10:24:04 +08:00
await timeout(0)
2021-10-18 18:52:29 +08:00
return {
selector: decodeURIComponent(to.hash),
offset: {
y: getScrollPaddingTopInPixels()
2021-10-18 18:52:29 +08:00
}
}
}
return {
x: 0,
y: 0
2020-08-13 11:47:56 +08:00
}
}