vue3-返回顶部组件

这篇博客详细介绍了如何在Vue项目中实现页面回顶功能。通过监听窗口滚动事件,当页面滚动到一定距离时显示返回顶部按钮。点击该按钮,利用定时器平滑滚动回顶部。代码中使用了`el-image`组件和自定义样式,同时包含鼠标悬停时的动画效果。
摘要由CSDN通过智能技术生成
<template>
  <div v-if="btnShow" class="to-top">
    <el-image class="to-top-img scaleBig" :src="BackTop" fit="cover" @click="backTop"></el-image>
  </div>
</template>

<script setup>
import {onMounted, ref} from "vue";
import BackTop from "../../assets/images/to-top.svg";
const btnShow=ref(false)
onMounted(() => {
  window.addEventListener('scroll',scrollToTop)
})
let timer=null;
function backTop(){
  timer=setInterval(function (){
    let backTop=window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
    let speedTop=backTop/10;
    document.documentElement.scrollTop=backTop-speedTop;
    if(backTop===0){
      clearInterval(timer)
    }
  },10);
}
function scrollToTop(){
  let pageLookHeight =document.documentElement.clientHeight || document.body.clientHeight
  let scroll= document.documentElement.scrollTop
  btnShow.value = scroll >= pageLookHeight * 0.618;
}
</script>

<style lang="scss" scoped>
.to-top{
  position: fixed;
  right: 50px;
  bottom: 50px;
  z-index: 2;
  border: 1px solid #333333;
  border-radius: 50%;
  width: 50px;
  height: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: all ease-in-out .5s;
  overflow: hidden;
  &-img{
    width: 40px;
    height: 40px;
  }
}

/*鼠标经过放大*/
.scaleBig{
  transition: transform 0.5s ease;
}
.scaleBig:hover{
  animation: hover_scale 1.5s ease-in-out infinite ;
}
@keyframes hover_scale {
  0% {transform: scale(1);}
  50% {transform: scale(1.2);}
  100% {transform: scale(1);}
}
</style>

图片
在这里插入图片描述

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值