vue3 按钮hover根据鼠标进入按钮的方位 从不同位置进入按钮按钮hover状态不同 hover根据鼠标位置

11 篇文章 0 订阅
8 篇文章 0 订阅

在这里插入图片描述
效果图

按钮的css样式在这篇文章 https://blog.csdn.net/SanOrintea/article/details/126220789

相关代码

<script setup>
import { ref, reactive, inject, computed, onMounted, onUnmounted } from 'vue'
// 定义按钮位置
const btn = ref() // 与html中ref=""对应,定位dom元素
const btnState = reactive({x:0,y:0})
// 定义[鼠标距离按钮的]相对位置
const mouseBtnRange = reactive({x:0,y:0})
const update = e=>{
    let x = e.pageX - btnState.x // [鼠标距离按钮的相对位置的]两条直角边的边长, e.pageX是鼠标绝对位置
    let y = e.pageY - btnState.y
    mouseBtnRange.x = -(props.animate * x / Math.sqrt(x**2 + y**2)).toFixed(2) + 'px' // 当斜边为animate时,等比缩小,求缩小后的[鼠标距离按钮的相对位置的]两条直角边边长。
    mouseBtnRange.y = -(props.animate * y / Math.sqrt(x**2 + y**2)).toFixed(2) + 'px'
}
onMounted(() => {
    // 计算按钮位置
    let btnDom = btn.value.getBoundingClientRect()
    btnState.x = btnDom.x + btnDom.width/2
    btnState.y = btnDom.y + btnDom.height/2
    // 监控鼠标位置
    window.addEventListener('mousemove',update)
}) 
onUnmounted(()=>{
    // 卸载监控鼠标位置
	window.removeEventListener('mousemove',update);
})
</script>

<template>
    <button 
        ref="btn"
        class="neumorphism"
        :style="{ 
            '--hover-sin':mouseBtnRange.x, '--hover-cos':mouseBtnRange.y,
         }"
    >
    {{btnState}}
    <br>
    {{mouseBtnRange}}
    </button>
</template>

<style>
.neumorphism:hover{
    transform: translate(var(--hover-sin),var(--hover-cos));
    transition: all .2s ease;
}
</style>

计算思路
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值