smooth scroll for hash anchors

pull/1/head
Evan You 5 years ago
parent 444b362dea
commit ae4102bef7

@ -3,8 +3,9 @@ import { reactive, provide } from 'vue'
export const RouteSymbol = Symbol() export const RouteSymbol = Symbol()
export function useRouter() { export function useRouter() {
const loc = location
const route = reactive({ const route = reactive({
path: location.pathname, path: loc.pathname,
scrollPosition: window.scrollY scrollPosition: window.scrollY
}) })
@ -16,18 +17,32 @@ export function useRouter() {
(e) => { (e) => {
if (e.target.tagName === 'A') { if (e.target.tagName === 'A') {
const { href, target } = e.target const { href, target } = e.target
const url = new URL(href)
if ( if (
target !== `_blank` && target !== `_blank` &&
href.startsWith(`${location.protocol}//${location.host}`) url.protocol === loc.protocol &&
url.hostname === loc.hostname
) { ) {
if (url.pathname === loc.pathname) {
// smooth scroll bewteen hash anchors in the same page
if (url.hash !== loc.hash) {
e.preventDefault()
window.scrollTo({
left: 0,
top: e.target.offsetTop,
behavior: 'smooth'
})
}
} else {
e.preventDefault() e.preventDefault()
// save scroll position before changing url // save scroll position before changing url
saveScrollPosition() saveScrollPosition()
history.pushState(null, '', href) history.pushState(null, '', href)
route.path = location.pathname route.path = loc.pathname
route.scrollPosition = 0 route.scrollPosition = 0
} }
} }
}
}, },
{ capture: true } { capture: true }
) )
@ -39,7 +54,7 @@ export function useRouter() {
*/ */
(e) => { (e) => {
route.path = location.pathname route.path = location.pathname
route.scrollPosition = e.state && e.state.scrollPosition || 0 route.scrollPosition = (e.state && e.state.scrollPosition) || 0
} }
) )

Loading…
Cancel
Save