vue.js 3.2.22:平滑回到顶部
一,代码:
GoTop.vue
<template> <div style="width:100%;height:100vh;background: #ffff00;display: flex;flex-direction: column;"> <!--用来标记顶部位置的元素--> <div id="topdiv" style="width:0px;height:0px;"></div> <img style="width:100%;" src="http://www.chenmaner.com/images/portfolio/003.jpg" /> <img style="width:100%;" src="http://www.chenmaner.com/images/portfolio/004.jpg" /> <img style="width:100%;" src="http://www.chenmaner.com/images/portfolio/005.jpg" /> <img style="width:100%;" src="http://www.chenmaner.com/images/portfolio/006.jpg" /> <img style="width:100%;" src="http://www.chenmaner.com/images/portfolio/007.jpg" /> <img style="width:100%;" src="http://www.chenmaner.com/images/portfolio/008.jpg" /> <img style="width:100%;" src="http://www.chenmaner.com/images/portfolio/009.jpg" /> <img style="width:100%;" src="http://www.chenmaner.com/images/portfolio/010.jpg" /> <!--回到顶部的按钮--> <div @click="goTop" v-if="showToScroll" class="el-backtop" style="position:fixed;width:40px;height:40px;right: 40px; bottom: 40px;"> <i class="el-icon el-backtop__icon"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024"><path fill="#409eff" d="M512 320 192 704h639.936z"></path></svg> </i> </div> </div> </template> <script> import {ref,onMounted,onUnmounted } from 'vue'; export default { name: "Image", setup() { onMounted(()=>{ //添加滚动事件 window.addEventListener('scroll',handleScroll,false) }) onUnmounted(()=>{ //移除滚动事件 window.removeEventListener('scroll',handleScroll) }) //回到顶部的按钮是否显示 const showToScroll = ref(false); //处理滚动,决定回到顶部的按钮是否显示出来 let handleScroll = () => { if (document.documentElement.scrollTop > 60) { showToScroll.value = true; } else { showToScroll.value = false; } } //回到顶部 const goTop = () => { document.querySelector("#topdiv").scrollIntoView({ behavior: "smooth", // 平滑过渡 block: "start" // }); } return { showToScroll, goTop, } } } </script> <style scoped> .el-backtop { position: fixed; background-color: #ffffff; width: 40px; height: 40px; border-radius: 50%; color: #409eff; display: flex; align-items: center; justify-content: center; font-size: 20px; box-shadow: 0 0 6px #0000001f; cursor: pointer; z-index: 5; } .el-backtop:hover { background-color: #f2f6fc; } .el-backtop__icon { font-size: 20px; } .el-icon { height: 1em; width: 1em; line-height: 1em; text-align: center; display: inline-block; position: relative; fill: currentColor; color: #409eff; } </style>
说明:刘宏缔的架构森林是一个专注架构的博客,
网站:https://blog.imgtouch.com
本文: https://blog.imgtouch.com/index.php/2023/05/28/vue-js-3-2-22-ping-hua-hui-dao-ding-bu/
对应的源码可以访问这里获取: https://github.com/liuhongdi/
或: https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
二,测试效果
位于顶部时:回到顶部的悬浮按钮默认不显示
滑动离开顶部时,按钮显示:
此时点击按钮会滑动回顶部
三,查看vue的版本:
lazy@0.1.0 /data/vue/lazy ├─┬ @vue/cli-plugin-babel@4.5.15 │ └─┬ @vue/babel-preset-app@4.5.15 │ └── vue@3.2.22 deduped └─┬ vue@3.2.22 └─┬ @vue/server-renderer@3.2.22 └── vue@3.2.22 deduped