7

我有这段 HTML

<div id="workflowEditor" class="workflow-editor">

    <div class="node" class="ui-widget" style="top:20px; left:40px;">
        <div class="ui-widget ui-widget-header ui-state-default">Header test</div>
        <div class="ui-widget ui-widget-content">Test Content</div>
    </div>

</div>

有了这个 CSS

.workflow-editor
{
    position: relative;
    overflow: auto;
}

.workflow-editor .node
{
    position: absolute;

    min-width: 64px;
    min-height: 64px;
}

比打电话

$(".node", "#workflowEditor").draggable({
    containment: [0, 0, 500, 500]
});

但是,拖动这个“节点”将允许拖动到负值;似乎draggable正在使用浏览器的视口坐标来限制边界框。有没有办法告诉坐标是相对于可拖动的父级的?

注意:父母可能会随着时间的推移改变位置。

** 编辑* *

可拖动对象所在的表面相对于其他一些内容。就像 CSS 指定的那样,我需要它是overflow:scroll;,因此如果将可拖动对象拖到外部,则将显示滚动条。父母的大小是固定的。我遇到的问题是可拖动对象可以拖动到表面的左侧(或顶部)(因此我丢失了它们)。我希望具有与将容器设置为类似的行为"parent",但允许可拖动对象溢出到父项的右侧/底部。

4

2 回答 2

5

计算节点及其父节点的边界,请 按照Jquery UI的解释检查jsFiddle 链接

var containmentX1 = $(".node").parent().offset().left;
var containmentY1 = $(".node").parent().offset().top;
var containmentX2 =  ($(".node").parent().outerWidth() +  $(".node").parent().offset().left - $('.node').outerWidth())
var containmentY2 = ($(".node").parent().outerHeight() +  $(".node").parent().offset().top - $('.node').outerHeight()) 

$(".node").draggable({
    containment:  [containmentX1, containmentY1, containmentX2, containmentY2]
});
于 2013-07-16T05:51:30.660 回答
0

I've had a similar problem - I needed to position "boxes" inside a container, allowing them to overflow to the bottom or the right, but not to the left or top. I also had to support varying the container's position.

Unfortunately, I could not find an elegant solution. As you correctly note, setting the containment via a coordinates array will establish document-related metrics, so we have to work with the position of the container relative to the document.

My little hack was to use the "document" position of the container for the top and left limits (I used jQuery offset [1], and a big enough value for right and bottom. I used the dragstart event [2] to re-read and reset the viewport position of the container (which updated the containment box to the current coordinates of the container, via the options method [3]).

var $containerEl = $('#container'),
    $draggableEl = $('#my-draggable');

$draggableEl.on('dragstart', function (e) {
    $(e.target).draggable('option',
                          'containment',
                          [ $containerEl.offset().left, $containerEl.offset().top, 15000, 15000 ]);
});

$draggableEl.draggable({
    containment: [ $containerEl.offset().left, $containerEl.offset().top, 15000, 15000 ]
});

[1] http://api.jquery.com/offset/

[2] http://api.jqueryui.com/draggable/#event-start

[3] http://api.jqueryui.com/draggable/#method-option

于 2014-12-09T16:12:41.157 回答