<template>
<div class="body"></div>
<div v-if="btnShow" style="position: fixed; right: 50px;bottom: 50px; z-index: 2">
<button class="scaleBig" @click="backTop">1213</button>
</div>
</template>
<script>
import { onMounted, ref } from "vue";
export default {
name: "Top",
setup() {
const btnShow = ref(false)
let timer = null; onMounted(() => {
window.addEventListener('scroll', scrollToTop)
})
const backTop=()=> {
timer = setInterval(function () {
let backTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
let speedTop = backTop / 5;
document.documentElement.scrollTop = backTop - speedTop; if (backTop === 0) {
clearInterval(timer)
}
}, 50);
}
const scrollToTop=()=> {
let pageLookHeight = document.documentElement.clientHeight || document.body.clientHeight
let scroll = document.documentElement.scrollTop
if (scroll >= pageLookHeight) {
btnShow.value = true
} else {
btnShow.value = false
}
}
return {
top, btnShow, timer, backTop, scrollToTop
}
}
}
</script>
<style scoped lang="scss">
.body{
height: 5000px;
width: 100%;
background-color: aquamarine;
}
.scaleBig {
transition: transform 0.5s ease;
}
.scaleBig:hover {
transform: scale(1.4);
}
</style>
vue3 返回顶部组件
最新推荐文章于 2025-03-06 14:50:52 发布
本文将介绍如何在 Vue3 项目中创建一个返回顶部的组件。通过监听滚动事件,实现当页面滚动到一定距离时显示返回顶部按钮,点击按钮则平滑滚动回页面顶部。我们将使用 Vue3 的 Composition API 来编写这个组件。
2210

被折叠的 条评论
为什么被折叠?



