Javascript drag and drop.... the receiving object?
Ive written some code so that i can drag an object, but eventually i wish to place this on a particular object and then call some functions.
How do i add a listener to the d开发者_C百科estination object, when i dont know which actual object will be dropped onto it?
In simple way you must attach some function on mousemove. This function must get round all dom elements and find your element. But it is DOM, and it so long. You must cache elemetns position and it will be fine.
i highly recommend using jquery ui draggable and droppable. no need to re-invent the wheel for this!
http://jqueryui.com/demos/draggable/
http://jqueryui.com/demos/droppable/
There are a couple ways that I've handled this in the past. They both depend on the cursor being outside the element you're dragging.
First, you could define a mouseup
event handler on the document level, and determine which element was the target of the event. That element will be the element that your draggable item was dropped on to, and you can handle the event from there.
Second, you could define a mouseup
event handler for each droppable area. This allows easier customization of the handler.
Keep in mind that both of these solutions rely on the cursor being outside the element you're dragging. Otherwise, the target of the event will always be the element you're dragging.
Do you simply want to have a 'drop' event on DOM elements but think you need to care what is being dropped onto them?
My initial approach to similar issues started with the 'drop', not the drag, but found that the 'ondrop' event is not very portable, implying I should use a framework like jQuery instead. See:
See here for a jQuery UI framework approach with demo:
- http://jqueryui.com/demos/droppable/
See here for a less framework oriented approach with some disscusion on the topic:
- http://www.useragentman.com/blog/2010/01/10/cross-browser-html5-drag-and-drop/
精彩评论