Skip to content

Commit

Permalink
perf: optimize a tag anchor jump
Browse files Browse the repository at this point in the history
  • Loading branch information
XPoet committed Nov 22, 2023
1 parent 5b74110 commit 632a182
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 25 deletions.
26 changes: 1 addition & 25 deletions source/js/post/toc.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,31 +43,7 @@ function initTOC() {
const target = document.getElementById(
decodeURI(element.getAttribute('href')).replace('#', '')
)
element.addEventListener('click', (event) => {
event.preventDefault()
let winScrollY = window.scrollY
winScrollY = winScrollY <= 1 ? -19 : winScrollY
let offset = target.getBoundingClientRect().top + winScrollY

if (!isHideHeader) {
offset = offset - 60
}

window.anime({
targets: document.scrollingElement,
duration: 500,
easing: 'linear',
scrollTop: offset,
complete: () => {
history.pushState(null, document.title, element.href)
if (isHideHeader) {
setTimeout(() => {
KEEP.utils.pageTopDom.classList.add('hide')
}, 150)
}
}
})
})
KEEP.utils.title2Top4HTag(element, target, isHideHeader, 500)
return target
})
}
Expand Down
39 changes: 39 additions & 0 deletions source/js/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -689,6 +689,44 @@ KEEP.initUtils = () => {
box.className = 'table-container'
element.wrap(box)
})
},

// H tag title to top
title2Top4HTag(a, h, isHideHeader, duration = 200) {
if (a && h) {
a.addEventListener('click', (e) => {
e.preventDefault()
let winScrollY = window.scrollY
winScrollY = winScrollY <= 1 ? -19 : winScrollY
let offset = h.getBoundingClientRect().top + winScrollY

if (!isHideHeader) {
offset = offset - 60
}

window.anime({
targets: document.scrollingElement,
duration,
easing: 'linear',
scrollTop: offset,
complete: () => {
history.pushState(null, document.title, a.href)
if (isHideHeader) {
setTimeout(() => {
KEEP.utils.pageTopDom.classList.add('hide')
}, 160)
}
}
})
})
}
},

// A tag anchor jump handle
aAnchorJump() {
document.querySelectorAll('a.headerlink').forEach((a) => {
this.title2Top4HTag(a, a, this.isHideHeader)
})
}
}

Expand All @@ -707,4 +745,5 @@ KEEP.initUtils = () => {
KEEP.utils.trimPostMetaInfoBar()
KEEP.utils.closeWebsiteAnnouncement()
KEEP.utils.wrapTableWithBox()
KEEP.utils.aAnchorJump()
}

0 comments on commit 632a182

Please sign in to comment.