jQuery UI draggable: get the underlaying element at drag-stop

点点圈 提交于 2019-12-11 02:57:33

问题


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()



来源:https://stackoverflow.com/questions/30390982/jquery-ui-draggable-get-the-underlaying-element-at-drag-stop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!