admin管理员组

文章数量:1208153

I have an outer div which catches onWheel mouse events. In the handler I would like to know the mouse pointer coordinates relative to the outer div. For example:

constructor() {
  this.handleWheel = this.handleWheel.bind(this);
}

handleWheel(event) {
  // how do I get mouse position relative to the outer div here?
}

render() {
  return (
    <div onWheel={this.handleWheel}>
      ...
      <img src="..." />
      ...
    </div>
  )
}

When I move mouse pointer over the image and scroll mousewheel, event.target is set to <img> and event.currentTarget is set to <div>. I can also get the mouse position relative to event.target (event.nativeEvent.offsetX/Y), but that doesn't help me because I don't know the position of <img> relative to <div>.

In other words, I'm stuck... How do I get the mouse position relative to the element that has a handler attached?

I have an outer div which catches onWheel mouse events. In the handler I would like to know the mouse pointer coordinates relative to the outer div. For example:

constructor() {
  this.handleWheel = this.handleWheel.bind(this);
}

handleWheel(event) {
  // how do I get mouse position relative to the outer div here?
}

render() {
  return (
    <div onWheel={this.handleWheel}>
      ...
      <img src="..." />
      ...
    </div>
  )
}

When I move mouse pointer over the image and scroll mousewheel, event.target is set to <img> and event.currentTarget is set to <div>. I can also get the mouse position relative to event.target (event.nativeEvent.offsetX/Y), but that doesn't help me because I don't know the position of <img> relative to <div>.

In other words, I'm stuck... How do I get the mouse position relative to the element that has a handler attached?

Share Improve this question asked Jan 22, 2018 at 19:44 johndodojohndodo 18.3k17 gold badges101 silver badges119 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 22

I have found a solution which works and am posting it here if it helps someone. I'm not sure though if it is the best one, so I would appreciate some comments (and possibly better solutions).

handleWheel(event) {
  let currentTargetRect = event.currentTarget.getBoundingClientRect();
  const event_offsetX = event.pageX - currentTargetRect.left,
        event_offsetY = event.pageY - currentTargetRect.top;
  //...
}

本文标签: javascriptMouse coordinates relative to currentTarget in React in event handlerStack Overflow