fix(theme): fix backToTop

修复 backToTop 按钮移动端交互问题
This commit is contained in:
pengzhanbo 2022-05-03 16:07:52 +08:00
parent 93e034fa9f
commit 48599f4dd2
5 changed files with 30 additions and 15 deletions

6
.vscode/launch.json vendored
View File

@ -1,6 +1,12 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "dev",
"request": "launch",
"type": "node-terminal",
"command": "pnpm run dev"
},
{
"name": "docs:dev",
"type": "node-terminal",

View File

@ -53,6 +53,7 @@
"nanoid": "^3.3.2",
"sass": "^1.49.9",
"sass-loader": "^12.6.0",
"ts-debounce": "^4.0.0",
"vue": "^3.2.33",
"vue-router": "^4.0.14",
"vuepress-plugin-comment2": "2.0.0-beta.47",

View File

@ -1,29 +1,23 @@
<script lang="ts" setup>
import { onMounted, onUnmounted, ref } from 'vue'
import { scrollTo } from '../utils'
import { debounce } from 'ts-debounce'
import { onMounted, ref } from 'vue'
import { getScrollTop, scrollTo } from '../utils'
import { BackTopIcon } from './icons'
const opacity = ref<number>(0)
const MAX_TOP = 300
const canShow = (): void => {
if (__VUEPRESS_SSR__) return
opacity.value = document.documentElement.scrollTop >= MAX_TOP ? 1 : 0
}
const canShow = debounce((): void => {
opacity.value = getScrollTop(document) >= MAX_TOP ? 1 : 0
})
const scrollToTop = (): void => {
scrollTo(document, 0)
}
onMounted(() => {
if (__VUEPRESS_SSR__) return
canShow()
window.addEventListener('scroll', canShow, false)
})
onUnmounted(() => {
if (__VUEPRESS_SSR__) return
window.removeEventListener('scroll', canShow)
window.addEventListener('scroll', () => canShow(), false)
})
</script>
<template>
@ -32,10 +26,11 @@ onUnmounted(() => {
</div>
</template>
<style lang="scss">
@import '../styles/variables';
.btn-back-top {
position: fixed;
right: 3rem;
bottom: 3rem;
bottom: 4.35rem;
width: 3rem;
height: 3rem;
text-align: center;
@ -60,4 +55,10 @@ onUnmounted(() => {
}
}
}
@media (max-width: $MQMobile) {
.btn-back-top {
right: 1.25rem;
bottom: 2rem;
}
}
</style>

View File

@ -11,7 +11,12 @@ export function getScrollTop(
target: Document | HTMLElement = document
): number {
if (target === document || !target) {
return document.documentElement.scrollTop || document.body.scrollTop
return (
window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop ||
0
)
} else {
return (target as HTMLElement).scrollTop
}

2
pnpm-lock.yaml generated
View File

@ -30,6 +30,7 @@ importers:
nanoid: ^3.3.2
sass: ^1.49.9
sass-loader: ^12.6.0
ts-debounce: ^4.0.0
vue: ^3.2.33
vue-router: ^4.0.14
vuepress-plugin-comment2: 2.0.0-beta.47
@ -65,6 +66,7 @@ importers:
nanoid: 3.3.3
sass: 1.51.0
sass-loader: 12.6.0_sass@1.51.0
ts-debounce: 4.0.0
vue: 3.2.33
vue-router: 4.0.14_vue@3.2.33
vuepress-plugin-comment2: 2.0.0-beta.47