思路
- 实时获取当前页面高度并监听高度变化
- 当高度超过设定的距离之后显示组件
- 点击组件即可返回顶部
封装组件
<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
const scrollTop = ref(0) // 距顶部距离
const visiable = ref(true) // 是否显示组件
//检测距离
function handleScroll() {
scrollTop.value =
document.documentElement.scrollTop ||
document.body.scrollTop
scrollTop.value > 500 ? (visiable.value = true) : (visiable.value = false)
}
// 动画帧函数
function step(){
window.scrollTo({
top:0,
behavior:"smooth"
})
}
onMounted(()=>{
window.addEventListener('scroll', handleScroll)
})
onUnmounted(()=>{
window.addEventListener('scroll', handleScroll)
})
</script>
<template>
<div class="icons" v-show="visiable" @click="step">
<!-- 需要显示的icon图标 -->
<img src="@/assets/LayoutIcon/back-top.png" class="icon" />
<p class="text">回到顶部</p>
</div>
</template>
<style scoped lang="scss">
.icons {
position: fixed;
right: 3rem;
bottom: 6rem;
width: 3.5rem;
height: 3.5rem;
padding: 0.5rem;
background-color: #fff;
box-shadow: 0px 3px 3px rgb(133, 133, 133);
cursor: pointer;
z-index: 999;
.icon {
size: 100%;
background-color: #fff;
}
.text {
display: none;
margin: 0;
text-align: center;
height: 3.5rem;
line-height: 7rem;
font: bold 100% Consolas, Monaco, monospace;
color: rgb(82, 53, 109);
}
&:hover {
.text {
display: block;
}
.icon {
display: none;
}
}
}
</style>
并全局挂载
使用
<BackToTop />