Vue SFC组合API中@mousemove事件在鼠标离开指定区域后仍触发问题求助
解决Vue中鼠标离开元素后mousemove事件持续触发的问题
问题原因
你的实现大概率是把mousemove事件绑定到了window或document这类全局对象上,但没在鼠标离开目标<div>时移除该监听,导致鼠标离开后事件还会持续触发。
解决方案
通过鼠标进入时添加全局监听、离开时移除监听,配合状态变量控制高亮元素的显示,就能解决这个问题:
- 模板中给目标元素绑定事件并通过
ref获取元素:
<template> <div ref="hoverTarget" class="target-area" @mouseenter="onMouseEnter" @mouseleave="onMouseLeave" > <!-- 目标区域内容 --> <div v-if="isHovering" class="highlight" :style="{ left: `${mouseX}px`, top: `${mouseY}px` }" ></div> </div> </template>
- Composition API中管理事件监听和状态:
<script setup> import { ref } from 'vue' const hoverTarget = ref(null) const isHovering = ref(false) const mouseX = ref(0) const mouseY = ref(0) // 更新高亮位置 const handleMouseMove = (e) => { const rect = hoverTarget.value.getBoundingClientRect() mouseX.value = e.clientX - rect.left mouseY.value = e.clientY - rect.top } // 鼠标进入时开启监听与高亮状态 const onMouseEnter = () => { isHovering.value = true window.addEventListener('mousemove', handleMouseMove) } // 鼠标离开时关闭监听与高亮状态 const onMouseLeave = () => { isHovering.value = false window.removeEventListener('mousemove', handleMouseMove) } </script>
- 补充基础样式:
<style scoped> .target-area { position: relative; width: 500px; height: 300px; border: 1px solid #ccc; } .highlight { position: absolute; width: 80px; height: 80px; border-radius: 50%; background: rgba(255, 0, 0, 0.2); pointer-events: none; /* 避免高亮元素干扰鼠标事件 */ transform: translate(-50%, -50%); /* 让高亮中心对齐鼠标位置 */ } </style>
关键注意点
- 添加和移除监听必须用同一个函数引用,不能用匿名函数,否则
removeEventListener无法匹配到对应的监听。 - 设置
pointer-events: none防止高亮元素拦截鼠标事件,确保目标区域的mouseleave能正常触发。 - 用
getBoundingClientRect()计算相对坐标,保证高亮位置在目标元素内正确偏移。
内容的提问来源于stack exchange,提问作者Audeo
相关产品推荐
相关产品推荐

