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

如何在mouseenter事件中获取鼠标进入位置并实现气泡定向移动?

能否在mouseenter事件中读取鼠标的进入位置?是否存在可获取的相关数据?

我制作了一个装满气泡的水箱,希望气泡能朝着鼠标光标触碰的方向移动(mouseenter事件绑定在气泡元素上)。

补充说明

附上水箱和气泡的截图:
tank bubbles pic

右侧为console.log输出的气泡属性(上方)与事件属性(鼠标坐标,下方),相关代码如下:

useEffect(() => {
    let bubbles = document.querySelectorAll(".bubble");

    const onMouseOverBub = (e, idx, stew) => {
      console.log(e)
      console.log(stew)
      
      gsap.to(`.bubble-${idx}`, {
        x: (stew.x - e.offsetX) + 360,
        y: (stew.y - e.offsetY) + 360,
        duration: 5
      })

      // gsap.to(`.bubble-${idx}`, {
      //   x: (stew.x + e.pageX) / 360,
      //   y: (stew.y + e.pageY) / 360,
      //   duration: 5
      // })
    }
    bubbles.forEach((el, idx) => {let stew = el.getBoundingClientRect(); el.addEventListener("mouseenter", (e) => onMouseOverBub(e, idx, stew))});
    
  }, [])

回答

完全可以在mouseenter事件中读取鼠标的进入位置,事件对象e包含了多组可用的坐标数据:

  • e.offsetX/e.offsetY:相对于气泡元素左上角的坐标,这正是你需要的「鼠标进入气泡的精确位置」
  • e.clientX/e.clientY:相对于浏览器视口的坐标
  • e.pageX/e.pageY:相对于整个文档的坐标

针对你让气泡朝鼠标触碰方向移动的需求,调整代码逻辑即可实现,核心要点:

  1. 不要提前缓存气泡的getBoundingClientRect()结果,应该在事件触发时实时获取,避免气泡位置变化后坐标失效
  2. 通过计算气泡中心与鼠标触碰点的方向向量,确定气泡的移动方向

修改后的代码示例:

useEffect(() => {
    let bubbles = document.querySelectorAll(".bubble");

    const onMouseOverBub = (e) => {
      const bubble = e.currentTarget;
      const stew = bubble.getBoundingClientRect();
      
      // 计算气泡中心的视口坐标
      const bubbleCenterX = stew.x + stew.width / 2;
      const bubbleCenterY = stew.y + stew.height / 2;
      // 计算鼠标触碰点的视口坐标
      const touchPointX = stew.x + e.offsetX;
      const touchPointY = stew.y + e.offsetY;
      
      // 计算移动方向向量(缩放系数0.5可根据需求调整)
      const moveX = (touchPointX - bubbleCenterX) * 0.5;
      const moveY = (touchPointY - bubbleCenterY) * 0.5;

      // 让气泡朝着触碰方向移动
      gsap.to(bubble, {
        x: `+=${moveX}`,
        y: `+=${moveY}`,
        duration: 5
      })
    }

    bubbles.forEach(el => {
      el.addEventListener("mouseenter", onMouseOverBub);
    });
    
  }, [])

内容的提问来源于stack exchange,提问作者nKc

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 09:05:22