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 badges1 Answer
Reset to default 22I 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
版权声明:本文标题:javascript - Mouse coordinates relative to currentTarget in React in event handler - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738745996a2110121.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论