You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 17:50:42