javascript - How to get mouse X position of a mouse event of a div (and not of its children) with React 17? - Stack Overflow

I have a simple snippet where I attach a onMouseMove listener to a given div:<div onMouseMove={hand

I have a simple snippet where I attach a onMouseMove listener to a given div:

<div onMouseMove={handleMouseMove}>
    <div>A</div>
    <div>B</div>
    <div>C</div>
</div>

I want to know the X position of the mouse pointer within the parent div where I attached the mouse listener to. However, the event seems to only contain references to the children divs (as target), and the root (as currentTarget).

The event's nativeEvent property also is not helping it seems.

I'm on React 17. I think this is making it harder as previously the currentTarget would point to that div where I placed the listener to, but on React 17 these listeners to the root.

How can I get the coordinates within the div I attached the listener to?

Thanks!

I have a simple snippet where I attach a onMouseMove listener to a given div:

<div onMouseMove={handleMouseMove}>
    <div>A</div>
    <div>B</div>
    <div>C</div>
</div>

I want to know the X position of the mouse pointer within the parent div where I attached the mouse listener to. However, the event seems to only contain references to the children divs (as target), and the root (as currentTarget).

The event's nativeEvent property also is not helping it seems.

I'm on React 17. I think this is making it harder as previously the currentTarget would point to that div where I placed the listener to, but on React 17 these listeners to the root.

How can I get the coordinates within the div I attached the listener to?

Thanks!

Share Improve this question asked Nov 12, 2021 at 17:02 Edy BourneEdy Bourne 6,20616 gold badges61 silver badges114 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

This works as expected in react version 17.0.2

function Component() {
  const onMouseMove = (e) => {
    let rect = e.currentTarget.getBoundingClientRect();
    let x = e.clientX - rect.left;
    let y = e.clientY - rect.top;

    console.log(x, y);
  };
  return (
    <div onMouseMove={onMouseMove}>
      <div>A</div>
      <div>B</div>
      <div>C</div>
    </div>
  );
}

Based on this answer and a ment on it, about using a currentTarget

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745241654a4618216.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信