jQuery UI Draggable: Update containment on drag event

瘦欲@ 提交于 2019-12-23 02:34:18

问题


Is this possible: Create a draggable element so that when it is dragged over a specific droppable element, the draggable element's containment option is set to the droppable element? This would create an effect where dragging something over a droppable element causes the draggable element to get locked/stuck to the confines of the droppable element.

Below is an excerpt from my code, although it fails to accomplish the above effect.

var droppable_position = $('#droppable').position();
$('#draggable').draggable({
    helper: 'clone',
    drag: function (event, ui) {
        if (ui.position.left > droppable_position.left && ui.position.top > droppable_position.top)
        {
            $('#draggable').draggable('option', 'containment', '#droppable');
        }
    }
});

回答1:


You could overwrite the position of the element being dragged.

Here is not the code "ready to go" but pieces permitting to develop yourself. The idea is to set containment positions variables in the hover event of your droppable element and test them with the current dragging position in the drag event of your dragging element.

This fiddle is an example of the position overriding : http://jsfiddle.net/QvRjL/74/

This fiddle is an example of how you could do to check if the dragged element is near a border of your container : http://jsfiddle.net/pPn3v/22/

Position overwriting example :

$(document).mousemove(function(e){
   window.mouseXPos = e.pageX;
   window.mouseYPos = e.pageY;
}); 

$('[id^="drag-"]').each(function() {
    $(this).draggable({
        opacity: 0.7,
        cursorAt: { top: 15, left: 50 },        
        scroll: true,
        stop: function(){},  
        drag : function(e,ui){            
            //Force the helper position
            ui.position.left = window.mouseXPos - $(this).draggable('option','cursorAt').left;
            ui.position.top = window.mouseYPos- $(this).draggable('option','cursorAt').top; 
        });
});


来源:https://stackoverflow.com/questions/13103368/jquery-ui-draggable-update-containment-on-drag-event

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