jQuery UI draggable: get the underlaying element a

2019-07-22 01:19发布

问题:

Is it possible to get the underlaying element of an dragged element?

My specific task is to drag a td element. If the dragstop event is fired I want the underlaying element. The underlaying element is also a td.

How could I achiev this?

Here is my HTML code:

<table class="grid">
     <tr>
         <td class="value" colspan="4"></td>
         <td></td>
     </tr>
     <tr>
         <td></td>
         <td></td>
         <td></td>
         <td></td>
         <td></td>
     </tr>
</table>

The jQuery part is here:

$('.value').draggable({
    cursor: "move",
    containment: ".grid",
    snap: "td",
    start: function(event, ui) {
        console.log("start", event, ui, $(this));
    },
    stop: function(event, ui) {
        console.log("stop", event, ui, $(this));
    }
});

If I drag the td with the class value and I stop dragging I want the td element under the value element.

Thanks in advance.

回答1:

There is a neat little function wich will find you the element on a specific function: document.elementFromPoint(x, y);

On SO I found a good solution to determine all elements on that position. I refer to this answer in my code:

$('.value').draggable({
    cursor: "move",
    containment: ".grid",
    snap: "td",
    start: function(event, ui) {
    },
    stop: function(event, ui) {

        var el = allElementsFromPoint(event.pageX, event.pageY);
        var td = $(el).filter('td').not($(this));
        td.css({'backgroundColor': 'red'});
    }
});

Demo

So the function will return all elements that lies at the specified position. To get the wanted td filter the elements to only contain tds and remove the dragged td.

Reference

.elementFromPoint()

.filter()

.not()