jquery draggable – 遏制

我有一个小项目,我正在研究,并使用jquery的draggable有一个有趣的收容问题:

基本上,我有两个div – 顶部和底部。 然后,我有一个第三个div,它是一个.draggable({}),可以拖动以调整顶部和底部div的大小。

– 看看这里: http : //jsfiddle.net/Kpt2K/7/

问题是,我无法按照我的意愿来控制拖动。 在上面的小提琴中,我把橙色放在我想要收容的地方开始和结束。

有趣的说明:我尝试做以下事情:

 $('#container').innerWrap('
'); var containerHeight = $('#container').height(); $('#containmentBox').css({'height': containerHeight - 45);

这使得遏制工作适用于底部,但不适用于顶部跨度。 所以,我认为我坚持使用containment: [x1,y1,x2,y2] ,但还没有完全掌握如何使用它。

看看小提琴,让我知道你可以想出什么来限制可拖动的运动到两个橙色跨度内。

包含选项允许数组在哪里设置包含它的位置。 试试这个:

 var containmentTop = $("#stop-top").position().top; var containmentBottom = $("#stop-bottom").position().top; $('#bar').draggable({axis: 'y', containment : [0,containmentTop,0,containmentBottom] }); 

JSFiddle的例子

您还可以使用helper:这将允许您添加一个div ,您可以动态设置可拖动操作发生之前的大小。 这允许您在收容中引用它,尽管它实际上并不是页面的一部分。 如果你使用start: ,那么当draggable函数查找包含元素时,这个div就不存在了。 你可以在stop:清理stop:

 $(<>).draggable({ helper: function (event, ui) { var target = $(this).clone(); var oBody = $(document).find('body'); var containmentDiv = $('
'); containmentDiv .css('top',calculatedTop) .css('left',calculatedLeft) .css('width',calculatedWidth) .css('height',calculatedHeight) .css('position','absolute'); containmentDiv.appendTo(oBody); target.children('div').remove(); target.css('background-color','#f00'); return target; }, stop: function(event, ui) { $(document).filter('body').find('#div_containment').remove(); }, containment: "#div_containment" //containment via selector });

您可以使用JavaScript对象引用在helper:设置计算值helper:其他

您可以在由2个停止元素分隔的边界框中约束包含:

 var top = $("#stop-top").offset().top + $("#stop-top").height(); var bottom = $("#stop-bottom").offset().top - $("#bar").height(); $('#bar').draggable({axis: 'y', containment : [0, top, 10000, bottom] }); 

JsFiddle: http : //jsfiddle.net/Kpt2K/9/

不可否认,文档很薄 – 我不得不做很多测试来弄明白。

我的错误在于认为包含数组定义了可拖动元素可以移动的边界,定义为[x,y,width,height],但我发现包含数组定义了左上角和右下角定义包含的元素原点可以在其中移动的[x1,y1,x2,y2]定义的边界。

这是有意义的,因为最后两个数组元素被定义为x2和y2(点属性),而不是w和h(矩形属性),但文档应该更具体地说明这些参数在所包含元素的上下文中的含义,以及在什么情况下(针对所包含的元素的起源)和坐标系(包含的元素)。