Vue中@mouseenter事件如何获取section元素的坐标?
解决Vue mouseenter事件中获取坐标的问题
你的问题核心是没有给事件处理函数传递鼠标事件对象,导致e为undefined,自然无法访问clientX/pageX等属性。
修复步骤:
你需要让Vue把鼠标事件对象传递给getCoords函数,有两种简单方式:
方式1:显式传递$event
在模板中调用函数时,手动传入Vue提供的$event变量:
<template> <!-- ... --> <section @mouseenter="getCoords($event)" /> </template>
方式2:直接绑定函数名
如果函数只需要事件对象作为参数,直接写函数名即可,Vue会自动把事件对象传进去:
<template> <!-- ... --> <section @mouseenter="getCoords" /> </template>
修复后的完整代码示例
<script setup> function getCoords(e) { // 现在能正常获取鼠标坐标了 const coords = { clientX: e.clientX, clientY: e.clientY, pageX: e.pageX, pageY: e.pageY } console.log(coords) // 后续动画逻辑... } </script> <template> <section @mouseenter="getCoords" /> </template>
补充说明
clientX/clientY:相对于浏览器可视区域的坐标pageX/pageY:相对于整个文档的坐标(包含滚动距离)- 两种方式任选其一即可,效果完全一致
内容的提问来源于stack exchange,提问作者Young Mamba
相关产品推荐
相关产品推荐

