前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >React技巧获取鼠标坐标位置

React技巧获取鼠标坐标位置

作者头像
chuckQu
发布2022-08-19 15:31:10
2.2K0
发布2022-08-19 15:31:10
举报
文章被收录于专栏:前端F2E

原文链接:https://bobbyhadz.com/blog/react-get-mouse-position[1]

作者:Borislav Hadzhiev[2]

正文从这开始~

总览

在React中获得鼠标位置:

  1. 在元素上设置onMouseMove属性,或者在window对象上添加事件监听器。
  2. 提供事件处理函数。
  3. event对象上访问相关属性。
代码语言:javascript
复制
import {useEffect, useState} from 'react';

export default function App() {
  const [coords, setCoords] = useState({x: 0, y: 0});

  const [globalCoords, setGlobalCoords] = useState({x: 0, y: 0});

  useEffect(() => {
    // 👇️ get global mouse coordinates
    const handleWindowMouseMove = event => {
      setGlobalCoords({
        x: event.screenX,
        y: event.screenY,
      });
    };
    window.addEventListener('mousemove', handleWindowMouseMove);

    return () => {
      window.removeEventListener('mousemove', handleWindowMouseMove);
    };
  }, []);

  const handleMouseMove = event => {
    setCoords({
      x: event.clientX - event.target.offsetLeft,
      y: event.clientY - event.target.offsetTop,
    });
  };

  return (
    <div>
      {/* 👇️ Get mouse coordinates relative to element */}
      <div
        onMouseMove={handleMouseMove}
        style={{padding: '3rem', backgroundColor: 'lightgray'}}
      >
        <h2>
          Coords: {coords.x} {coords.y}
        </h2>
      </div>

      <hr />

      <h2>
        Global coords: {globalCoords.x} {globalCoords.y}
      </h2>
    </div>
  );
}

react-get-mouse-position.gif

鼠标移动事件

上面代码向我们展示了,如何在div元素或者window对象上处理mousemove事件。

当鼠标指针的热点在一个元素内时,用户的鼠标被移动,mousemove事件就会在该元素上触发。

为了得到相对于页面上某个元素的鼠标坐标,我们必须从clientX减去offsetLeft,从clientY减去offsetTop

代码语言:javascript
复制
// 👇️ get mouse coords relative to the an element
const handleMouseMove = event => {
  setCoords({
    x: event.clientX - event.target.offsetLeft,
    y: event.clientY - event.target.offsetTop,
  });
};

offsetLeft属性返回当前元素的左上角在offsetParent节点内向左偏移的像素数。offsetTop属性返回当前元素的外边界相对于,位置最近的祖先元素的内边界之间的像素数。

clientX属性返回事件发生时,在应用程序视口中的水平坐标。clientY属性返回事件发生时,在应用程序视口中的垂直坐标。

监听鼠标事件

第二个示例向我们展示了,为了得到全局鼠标坐标,如何在window对象上监听mousemove事件。

代码语言:javascript
复制
useEffect(() => {
  // 👇️ get global mouse coordinates
  const handleWindowMouseMove = event => {
    setGlobalCoords({
      x: event.screenX,
      y: event.screenY,
    });
  };
  window.addEventListener('mousemove', handleWindowMouseMove);

  return () => {
    window.removeEventListener('mousemove', handleWindowMouseMove);
  };
}, []);

我们为useEffect 钩子传递空的依赖数组,因为我们只想在组件挂载时,注册mousemove 一次。

当组件卸载时,从useEffect 钩子返回的函数会被调用。

我们使用removeEventListener 方法来移除之前注册的事件监听。清理步骤很重要,因为我们要确保我们的应用程序中没有任何内存泄漏。

screenX/Y属性

screenX属性返回全局坐标中鼠标的水平坐标(偏移)。

screenY属性返回全局坐标中鼠标的垂直坐标(偏移)。

参考资料

[1]

https://bobbyhadz.com/blog/react-get-mouse-position: https://bobbyhadz.com/blog/react-get-mouse-position

[2]

Borislav Hadzhiev: https://bobbyhadz.com/about

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-05-29,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 前端F2E 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 总览
  • 鼠标移动事件
  • 监听鼠标事件
  • screenX/Y属性
    • 参考资料
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档