如何在Vue+Vuetify的v-card组件上实现自定义鼠标悬停效果
问题核心原因
- 自定义CSS变量的绑定格式错误,未按照CSS变量规范使用
--前缀,或绑定位置没有作用到v-card的根DOM节点 - scoped样式规则书写错误,错误使用
deep修饰符导致变量无法被正确识别 - 事件触发对象使用错误,使用
e.target而非e.currentTarget获取元素边界,导致坐标绑定逻辑异常 v-card未设置overflow: hidden属性,导致悬停渐变伪元素超出可视范围无法显示
修复方案
- 正确绑定CSS变量到
v-card根节点
直接在v-card标签上绑定style属性,变量名必须以双横杠开头,格式如下:
<template> <v-card @mousemove="handleCardHover" :style="{ '--mouse-x': `${mouseX}px`, '--mouse-y': `${mouseY}px` }" class="custom-hover-card" > <!-- 卡片内部内容插槽 --> </v-card> </template>
- 修正坐标计算逻辑
使用e.currentTarget获取绑定事件的卡片根节点计算相对坐标,避免子元素触发事件导致坐标偏移:
<script setup> import { ref } from 'vue' const mouseX = ref(0) const mouseY = ref(0) const handleCardHover = (e) => { const cardBound = e.currentTarget.getBoundingClientRect() mouseX.value = e.clientX - cardBound.left mouseY.value = e.clientY - cardBound.top } </script>
- 调整样式规则
单文件组件scoped样式下无需添加deep修饰符,直接对应绑定的卡片类名编写样式即可,注意开启overflow: hidden避免伪元素溢出:
<style scoped> .custom-hover-card { position: relative; overflow: hidden; } .custom-hover-card::before { content: ''; position: absolute; inset: 0; background: radial-gradient( circle at var(--mouse-x) var(--mouse-y), rgba(255, 255, 255, 0.12), transparent 70% ); opacity: 0; transition: opacity 0.25s ease; pointer-events: none; z-index: 1; } .custom-hover-card:hover::before { opacity: 1; } </style>
内容的提问来源于stack exchange,提问作者Alex T
相关产品推荐
相关产品推荐

