【效果】回到顶部功能实现

实现效果:

相关代码:

javascript 复制代码
<template>
    <div class="cats" :style="{ top: catsTop }" ref="cats" @click="catTop"></div>
</template>

样式:

javascript 复制代码
/* 回到顶部 - 小猫咪 */
.cats {
    position: fixed;
    right: 56px;
    top: -80px;
    z-index: 9999;
    width: 64px;
    height: 64px;
    transform: translateX(50%);
    background: url('@/assets/images/cat.png') no-repeat center center / contain;
    cursor: pointer;
}

.cats::after {
    position: absolute;
    content: '别滚动了~';
    right: 55%;
    top: -110%;
    width: 100px;
    height: 100px;
    display: flex;
    justify-content: center;
    align-items: center;
    background: url('@/assets/images/cat-word.png') no-repeat center center / contain;
    font-size: 14px;
    color: rgb(57, 197, 187);
    padding-top: 6px;
    box-sizing: border-box;
    opacity: 0;
    transition: all .2s ease-in-out;
    pointer-events: none;
}

.cats.bottom::after {
    opacity: 1;
}

功能:

javascript 复制代码
import { ref,onMounted,onUnmounted,nextTick } from 'vue';
    const cats = ref<HTMLElement | null>(null);  
    const catsTop = ref('-80px')
    let doctH = 0 // 文档高度
    let viewH = 0 // 可视区域高度
 
    //点击后跳转至顶部
    const catTop = () => {
        document.documentElement.scrollTop = document.body.scrollTop = 0
    }
    
	//滚动时运行代码,用于计算滚动位置
    const calcScroll = () => {
        const scroll = document.documentElement.scrollTop || document.body.scrollTop
        const hideH = doctH - viewH
        let rate = scroll / hideH
		if(rate>=1){
			rate=1
		}
        const result = Math.floor(viewH * rate)
        catsTop.value = `${result - 128}px`
        doctH === scroll + viewH ? cats.value?.classList.add('bottom') : cats.value?.classList.remove('bottom')
    }

    onMounted(async () => {
		await nextTick(() => {
			//将浏览器视口中可视区域的高度(不包括滚动条、工具栏等)赋值给变量 doctH
            doctH = document.documentElement.scrollHeight
			//获取浏览器视口高度的标准属性
            viewH = window.innerHeight || document.documentElement.clientHeight
            window.addEventListener('scroll', calcScroll)
        })
    })

    onUnmounted(() => {
        window.removeEventListener('scroll', calcScroll)
		
    })
相关推荐
航Hang*2 分钟前
第3章:Linux系统安全管理——第1节:Linux 防火墙部署(firewalld)
linux·服务器·网络·学习·系统安全·vmware
云飞云共享云桌面2 分钟前
SolidWorks三维设计不用单独买电脑,1台服务器10个设计用
运维·服务器·数据库·3d·电脑
Rabbit_QL2 分钟前
从服务器拷文件到本地:scp 与 rsync 实战
服务器
acaad6 分钟前
访问信创系统的服务器报错Received fatal alert: handshake_failure
运维·服务器
大树887 分钟前
【无标题】
大数据·运维·服务器·人工智能
幼儿园技术家7 分钟前
嵌套 H5 的跨端通信:iOS / Android / 小程序 / 浏览器
前端·js or ts
南境十里·墨染春水8 分钟前
linux学习进展 基础命令 vi基础命令
linux·运维·服务器·笔记·学习
冰暮流星15 分钟前
javascript之dom访问属性
开发语言·javascript·dubbo
一只小阿乐18 分钟前
TypeScript中的React开发
前端·javascript·typescript·react
江畔何人初22 分钟前
GTID的作用
linux·运维·服务器·mysql·云原生·kubernetes