fix: tolerant invalid hash (#399)

pull/421/head
Anthony Fu 3 years ago committed by GitHub
parent 4b76617621
commit efc5e1b256
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -84,9 +84,14 @@ export function createRouter(
if (inBrowser) { if (inBrowser) {
nextTick(() => { nextTick(() => {
if (targetLoc.hash && !scrollPosition) { if (targetLoc.hash && !scrollPosition) {
const target = document.querySelector( let target: HTMLElement | null = null
decodeURIComponent(targetLoc.hash) try {
) as HTMLElement target = document.querySelector(
decodeURIComponent(targetLoc.hash)
) as HTMLElement
} catch (e) {
console.warn(e)
}
if (target) { if (target) {
scrollTo(target, targetLoc.hash) scrollTo(target, targetLoc.hash)
return return
@ -176,9 +181,16 @@ export function useRoute(): Route {
} }
function scrollTo(el: HTMLElement, hash: string, smooth = false) { function scrollTo(el: HTMLElement, hash: string, smooth = false) {
const target = el.classList.contains('.header-anchor') let target: Element | null = null
? el
: document.querySelector(decodeURIComponent(hash)) try {
target = el.classList.contains('.header-anchor')
? el
: document.querySelector(decodeURIComponent(hash))
} catch (e) {
console.warn(e)
}
if (target) { if (target) {
const targetTop = (target as HTMLElement).offsetTop const targetTop = (target as HTMLElement).offsetTop
// only smooth scroll if distance is smaller than screen height. // only smooth scroll if distance is smaller than screen height.

Loading…
Cancel
Save