效果图
按钮的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>
计算思路