From 632a182139711833b98c1ddefe836d9d10d515d2 Mon Sep 17 00:00:00 2001 From: XPoet Date: Wed, 22 Nov 2023 22:34:58 +0800 Subject: [PATCH] perf: optimize a tag anchor jump --- source/js/post/toc.js | 26 +------------------------- source/js/utils.js | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 25 deletions(-) diff --git a/source/js/post/toc.js b/source/js/post/toc.js index 56fc54fe..655e9c1d 100644 --- a/source/js/post/toc.js +++ b/source/js/post/toc.js @@ -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 }) } diff --git a/source/js/utils.js b/source/js/utils.js index 58056f5d..2922304e 100644 --- a/source/js/utils.js +++ b/source/js/utils.js @@ -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) + }) } } @@ -707,4 +745,5 @@ KEEP.initUtils = () => { KEEP.utils.trimPostMetaInfoBar() KEEP.utils.closeWebsiteAnnouncement() KEEP.utils.wrapTableWithBox() + KEEP.utils.aAnchorJump() }