1

我正在使用 jQuery 可拖动插件并面临下一个问题。可拖动创建后,插件不应用指定的包含选项。

在这里你可以找到一个例子:http: //jsfiddle.net/qQYsj/

// Containment will be applied after first move attempt
$('.item').draggable({ containment: [100, 100, 200, 200] });

有没有一种方法可以在没有额外逻辑的情况下应用包含,它将计算允许的位置并将元素放置到它?(这个逻辑已经存在于插件中)

谢谢。

4

3 回答 3

1

不确定这是否是您正在寻找的,但这可能是一个选择......

.item
{
    width: 100px;
    height: 100px;
    border: 1px solid red;
    position: absolute;
}


// Containment will be applied after first move attempt
var xpos = 100,
    ypos = 100;
$('.item').css({
    "top": ypos+"px",
    "left": xpos+"px"
  }).draggable({ containment: [ypos, xpos, 200, 200] });

http://jsfiddle.net/qQYsj/1/

于 2013-05-17T17:35:21.400 回答
0

我认为您的可拖动容器正在按预期工作。不过,您的可拖动元素不在该容器内。

为什么不一开始就使用 CSS 将您的.item内容放在收容区域内呢?

jsFiddle

.item
{
    position:absolute;
    top: 100px;
    left:100px;
    width: 100px;
    height: 100px;
    border: 1px solid red;
}

再想一想,当您说“模拟拖动”时,您是在谈论这样的事情:

jsfiddle2

// drag will start after dragging 100px
$('.item').draggable({ 
    containment: [100, 100, 200, 200],
    distance: 100
});
于 2013-05-19T00:51:28.307 回答
0

如果不添加重复逻辑,我没有找到任何可能的解决方案(可拖动插件中已经存在定位算法,但我无法强制插件执行它)。

所以我添加了下一个代码来更新项目位置:

function updateItemPosition(item, container)
{
    var itemRect = getRect(item), currentPosition = item.position(),
        position = getItemPosition(getRect(container), itemRect);

    item.css('top', position.top - itemRect.top + currentPosition.top + 'px')
        .css('left', position.left - itemRect.left + currentPosition.left + 'px');
}

function getRect(target)
{
    var result = target.offset();

    result.width = target.outerWidth();
    result.height = target.outerHeight();

    return result;
}

function getItemPosition(containerRect, itemRect)
{
    var result = {};

    result.top = Math.max(containerRect.top, Math.min(containerRect.top + containerRect.height - itemRect.height, itemRect.top));
    result.left = Math.max(containerRect.left, Math.min(containerRect.left + containerRect.width - itemRect.width, itemRect.left));

    return result;
}

它应该像这样使用:

updateItemPosition($('.item'), $('.placeholder'));
于 2013-05-20T16:59:24.410 回答