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

实现效果:

相关代码:

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)
		
    })
相关推荐
薛一半28 分钟前
React的数据绑定
前端·javascript·react.js
爱看书的小沐29 分钟前
【小沐杂货铺】基于Three.js渲染三维无人机Drone(WebGL / vue / react )
javascript·vue.js·react.js·无人机·webgl·three.js·drone
天若有情6733 小时前
从 try-catch 回调到链式调用:一种更优雅的 async/await 错误处理方案
前端·异常处理·前端开发·async·异步·await·异步编程
ShenJLLL7 小时前
vue部分知识点.
前端·javascript·vue.js·前端框架
恋猫de小郭8 小时前
你是不是觉得 R8 很讨厌,但 Android 为什么选择 R8 ?也许你对 R8 还不够了解
android·前端·flutter
PineappleCoder8 小时前
告别“幻影坦克”:手把手教你丝滑规避布局抖动,让页面渲染快如闪电!
前端·性能优化
暴力求解8 小时前
Linux---进程(五)进程调度
linux·运维·服务器
wsad05329 小时前
Linux 用户和组管理完整指南(中英文参数对照)
linux·运维·服务器
武帝为此9 小时前
【Shell变量替换与测试】
前端·chrome
CappuccinoRose9 小时前
CSS 语法学习文档(十九)
前端·css·属性·flex·grid·学习资源·格式化上下文