From 9e85f4d1c2984aa515035559b27708976bc4d7ad Mon Sep 17 00:00:00 2001 From: tangly1024 Date: Thu, 31 Oct 2024 20:57:34 +0800 Subject: [PATCH] =?UTF-8?q?Starter=E4=B8=BB=E9=A2=98=E6=BB=9A=E5=8A=A8?= =?UTF-8?q?=E6=8C=89=E9=92=AEbug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- themes/starter/components/BackToTopButton.js | 60 ++++++++++---------- 1 file changed, 31 insertions(+), 29 deletions(-) diff --git a/themes/starter/components/BackToTopButton.js b/themes/starter/components/BackToTopButton.js index 340b5b31..f6876021 100644 --- a/themes/starter/components/BackToTopButton.js +++ b/themes/starter/components/BackToTopButton.js @@ -7,40 +7,12 @@ import { useCallback, useEffect } from 'react' */ export const BackToTopButton = () => { useEffect(() => { - // ====== scroll top js - function scrollTo(element, to = 0, duration = 500) { - const start = element.scrollTop - const change = to - start - const increment = 20 - let currentTime = 0 - - const animateScroll = () => { - currentTime += increment - - const val = Math.easeInOutQuad(currentTime, start, change, duration) - - element.scrollTop = val - - if (currentTime < duration) { - setTimeout(animateScroll, increment) - } - } - - animateScroll() - } - Math.easeInOutQuad = function (t, b, c, d) { t /= d / 2 if (t < 1) return (c / 2) * t * t + b t-- return (-c / 2) * (t * (t - 2) - 1) + b } - const backToTop = document.querySelector('.back-to-top') - if (backToTop) { - backToTop.onclick = () => { - scrollTo(document.documentElement) - } - } window.addEventListener('scroll', navBarScollListener) return () => { @@ -61,10 +33,40 @@ export const BackToTopButton = () => { }, throttleMs) ) + // ====== scroll top js + function scrollTo(element, to = 0, duration = 500) { + const start = element.scrollTop + const change = to - start + const increment = 20 + let currentTime = 0 + + const animateScroll = () => { + currentTime += increment + + const val = Math.easeInOutQuad(currentTime, start, change, duration) + + element.scrollTop = val + + if (currentTime < duration) { + setTimeout(animateScroll, increment) + } + } + + animateScroll() + } + + function scrollTop() { + if (document) { + scrollTo(document.documentElement) + } + } + return ( <> {/* */} - + {/* */}