jQuery get mouse position within an element

2018-12-31 21:43发布

I was hoping to craft a control where a user could click inside a div, then drag the mouse, then let up on the mouse in order to indicate how long they want something to be. (This is for a calendar control, so the user will be indicating the length, in time, of a certain event)

It looks like the best way to do this would be to register a "mousedown" event on the parent div that in turn registers a "mousemove" event on the div until a "mouseup" event is triggered. The "mousedown" and "mouseup" events will define the start and end of the time range and as I follow "mousemove" events, I can dynamically change the size of the range so that the user can see what they are doing. I based this off of how events are created in google calendar.

The issue I'm having is that the jQuery event seems to only provide reliable mouse coordinate information in reference to the whole page. Is there any way to discern what the coordinates are in reference to the parent element?

Edit:

Heres a picture of what I'm trying to do: alt text

8条回答
人间绝色
2楼-- · 2018-12-31 22:19

If you make your parent element be "position: relative", then it will be the "offset parent" for the stuff you're tracking mouse events over. Thus the jQuery "position()" will be relative to that.

查看更多
旧人旧事旧时光
3楼-- · 2018-12-31 22:24

I would suggest this:

e.pageX - this.getBoundingClientRect().left
查看更多
登录 后发表回答