Resizing a JQuery Draggable element's containment parent while dragging

帅比萌擦擦* 提交于 2019-12-20 03:18:09

问题


I have a div 'slide' element within another div 'box' parent container and have applied JQuery Draggable to the child. While the item is being dragged, I'm resizing the parent container, sometimes shrinking, sometimes enlarging it.

The problem is that JQuery doesn't respond to this resizing and still contains the dragged element within the original dimensions of the parent, rather than within its current size, until mouseup - the next drag session will use the new dimensions (until it changes again).

To try and solve this, I was hoping to trigger the mouseup event followed by the mousedown event, so that JQuery will use the new container size:

$('.slide').draggable({ axis: "x", containment: 'parent',
                    drag: function (e, ui) {
                        resizeContainer();

                        if (outsideContainer()){

                        // Try to stop and restart dragging
                            $(this).trigger('mouseup');
                            $(this).trigger('mousedown');
                        }
                    }

However, this throws an exception...

Unable to get value of the property '0': object is null or undefined

...on this line of JQuery code:

this.helper[0].style.left=this.position.left+"px";

Anyone know how I can either a) get Draggable to respond real-time to the change in parent dimensions or b) trigger a dragstop and then dragend seamlessly?

Thanks.


回答1:


@Fijjit, if I understand correctly, what you want is a custom "containment" function, which implements your resizeContainer algorithm before applying bounds to the dragged element.

In the code below,

  • the standard draggable containment option is omitted
  • resizeContainer is attached as the draggable drag event handler
  • resizeContainer is dual purpose; (a) it performs your resize algorithm and (b) applies the custom containment algorithm

javascript:

$(function(){
    var $container = $("#myContainer");

    function resizeContainer(e, ui) {
        //implement container resize algorithm here
        var w1 = ui.helper.outerWidth(),
            w2 = $container.width();
        ui.position.left = Math.max(Math.min(ui.position.left, w2 - w1), 0);
    }

    $("#draggable").draggable({
        axis: "x",
        drag: resizeContainer
    });
});

See fiddle demo



来源:https://stackoverflow.com/questions/10456234/resizing-a-jquery-draggable-elements-containment-parent-while-dragging

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