Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

mouseevent - jQuery get mouse position within an element

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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One way is to use the jQuery offset method to translate the event.pageX and event.pageY coordinates from the event into a mouse position relative to the parent. Here's an example for future reference:

$("#something").click(function(e){
   var parentOffset = $(this).parent().offset(); 
   //or $(this).offset(); if you really just want the current element's offset
   var relX = e.pageX - parentOffset.left;
   var relY = e.pageY - parentOffset.top;
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...